﻿
Imports System.Data.SqlClient

''' <summary>
''' 約客明細界面
''' </summary>
''' <remarks></remarks>
Public Class Frm_OFSArrangeDeliveryDetail

#Region "Variabled Define"

    ''' <summary>
    ''' 路線表
    ''' </summary>
    ''' <remarks></remarks>
    Private BSC_AreaSetDtab As New DataTable

    ''' <summary>
    ''' 銷售定單主表
    ''' </summary>
    ''' <remarks></remarks>
    Private Sal_SaleOrdeA As New DataTable

    ''' <summary>
    ''' Sal_SaleOrdeA副本
    ''' </summary>
    ''' <remarks></remarks>
    Private SaleOrdeACopy As New DataTable


    ''' <summary>
    ''' 已安排的銷售定單主表
    ''' </summary>
    ''' <remarks></remarks>
    Private Sal_SaleOrdeAP As New DataTable

    ''' <summary>
    ''' 窗體是否已加載
    ''' </summary>
    ''' <remarks></remarks>
    Private fLoadBool As Boolean = False

    ''' <summary>
    ''' Tabpags Hash
    ''' </summary>
    ''' <remarks></remarks>
    Private TabHash As New Hashtable

    ''' <summary>
    ''' 服務器時間
    ''' </summary>
    ''' <remarks></remarks>
    Private fDateValue As Date

    ''' <summary>
    ''' 是否可以勾選
    ''' </summary>
    ''' <remarks></remarks>
    Private fCheckBool As Boolean = False

    ''' <summary>
    ''' 定金比率
    ''' </summary>
    ''' <remarks></remarks>
    Private fPercentage As String

    ''' <summary>
    ''' 狀態
    ''' </summary>
    ''' <remarks></remarks>
    Private Action As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    ''' <summary>
    ''' 是否是編輯模式
    ''' </summary>
    ''' <remarks></remarks>
    Private IsEditMode As Boolean = False

    ''' <summary>
    ''' 向前
    ''' </summary>
    ''' <remarks></remarks>
    Private btnPrevious As Button

    ''' <summary>
    ''' 向後
    ''' </summary>
    ''' <remarks></remarks>
    Private btnNext As Button

    ''' <summary>
    ''' 加載貨品類別
    ''' </summary>
    ''' <remarks></remarks>
    Private GoodsTypeDtab As New DataTable

    ''' <summary>
    ''' 是否是選擇事件
    ''' </summary>
    ''' <remarks></remarks>
    Private AfterCheckBool As Boolean = False

    ''' <summary>
    ''' 是否正在驗證
    ''' </summary>
    ''' <remarks></remarks>
    Private IsValidated As Boolean = False

    ''' <summary>
    ''' 車次表
    ''' </summary>
    ''' <remarks></remarks>
    Private Dtab_Truck As New DataTable

    ''' <summary>
    ''' 記錄是否是樹結點選擇事件
    ''' </summary>
    ''' <remarks></remarks>
    Private fTreeSelectChanged As Boolean = False

    ''' <summary>
    ''' fCellSelect=false 是不激發網格改變事件
    ''' </summary>
    ''' <remarks></remarks>
    Private fCellSelect As Boolean = True

    ''' <summary>
    ''' 記錄是先擇行改變了
    ''' </summary>
    ''' <remarks></remarks>
    Private fRowValidated As Boolean = False


#End Region

#Region "Property Define"

    ''' <summary>
    ''' 路線表
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_BSC_AreaSetDtab() As DataTable
        Get
            Return BSC_AreaSetDtab
        End Get
        Set(ByVal value As DataTable)
            BSC_AreaSetDtab = value
        End Set
    End Property

    ''' <summary>
    ''' 定單主表
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_Sal_SaleOrdeA() As DataTable
        Get
            Return Sal_SaleOrdeA
        End Get
        Set(ByVal value As DataTable)
            Sal_SaleOrdeA = value
            ''保留副本
            SaleOrdeACopy = Sal_SaleOrdeA.Copy
        End Set
    End Property

    ''' <summary>
    ''' 已安排的銷售定單主表
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_Sal_SaleOrdeAP() As DataTable
        Get
            Return Sal_SaleOrdeAP
        End Get
        Set(ByVal value As DataTable)
            Sal_SaleOrdeAP = value
        End Set
    End Property

    ''' <summary>
    ''' 定金比率
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_fPercentage() As String
        Get
            Return fPercentage
        End Get
        Set(ByVal value As String)
            fPercentage = value
        End Set
    End Property

    ''' <summary>
    ''' 狀態
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_Action() As IDServer.IDServer.ActionBtn
        Get
            Return Action
        End Get
        Set(ByVal value As IDServer.IDServer.ActionBtn)
            Action = value
        End Set
    End Property

    ''' <summary>
    ''' 向前
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_btnPrevious() As Button
        Get
            Return btnPrevious
        End Get
        Set(ByVal value As Button)
            btnPrevious = value
        End Set
    End Property

    ''' <summary>
    ''' 向後
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_btnNext() As Button
        Get
            Return btnNext
        End Get
        Set(ByVal value As Button)
            btnNext = value
        End Set
    End Property

    ''' <summary>
    ''' 車次表
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Set_Dtab_Truck() As DataTable
        Get
            Return Dtab_Truck
        End Get
        Set(ByVal value As DataTable)
            Dtab_Truck = value
        End Set
    End Property

#End Region

#Region "Method Define"

#Region "Initialize"

    ''' <summary>
    ''' 初始化事件
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Initialze()
        Try

            fDateValue = ServerDate
            Me.CheckBox2.Checked = True

            Me.dtpStartDate.Text = Format(DateAdd(DateInterval.Day, -1, fDateValue), "yyyy-MM-dd")
            Me.dtpEndDate.Text = Format(fDateValue, "yyyy-MM-dd")
            Me.dtpfDeliverDateStart.Text = Format(fDateValue, "yyyy-MM-dd")
            Me.dtpfDeliverDateEnd.Text = Format(fDateValue, "yyyy-MM-dd")

            Me.dtpfDeliverDateStart.Enabled = False
            Me.dtpfDeliverDateEnd.Enabled = False

            Dim Dset As New DataSet
            Dset = Me.InitialDset()
            Me.GoodsTypeDtab = Dset.Tables(1)
            FillCombox(Dset.Tables(0))
            Load_TreeView(Me.Tvw_1_1, "全部", True)
            Load_TreeView(Me.Tvw_1_2, "全部", True, True)
            Load_TreeView(Me.Tvw_2_1, "全部", True, False)
            Load_TreeView(Me.Tvw_3_1, "全部", False, False)
            AddHandlers_IContexMenu(Me.ContextMenuStrip1)
            FillComboxForEnum(cbxfDestineStatus, GetType(E_DestineStatus), 1)
            Me.TabHash = AddTabpagesToHash()

        Catch ex As Exception
            MessageBox.Show("Initialze:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    ''' <summary>
    ''' 保存已設計好的TabPages 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function AddTabpagesToHash() As Hashtable
        Dim Hash As New Hashtable

        For Each Pag As TabPage In Me.TabControl1.TabPages
            Dim TabName As String = Pag.Name
            Hash.Add(TabName, Pag)
        Next

        Return Hash
    End Function

    ''' <summary>
    ''' 動態添加TagPage
    ''' </summary>
    ''' <param name="TabName"></param>
    ''' <remarks></remarks>
    Public Sub DynamicAddTabpage(ByVal TabName As String)
        Try
            Me.TabControl1.TabPages.Clear()
            Dim Pag As TabPage = DirectCast(Me.TabHash(TabName), TabPage)

            If Not Pag Is Nothing Then
                Me.TabControl1.TabPages.Add(Pag)
            End If

        Catch ex As Exception
            MsgBox("DynamicAddTabpage:" & ex.Message & ex.StackTrace, MsgBoxStyle.Critical And MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 返回網格列標頭
    ''' </summary>
    ''' <param name="Index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_CaptionHash(ByVal Index As Integer) As Hashtable
        Dim Hash As New Hashtable
        Try
            With Hash
                Select Case Index
                    Case 1
                        .Add("fGoodsBarCode", "貨品條碼")
                        .Add("GoodsName", "貨品名稱")
                        .Add("SupperItem", "産商編號")
                        .Add("ColorSName", "貨品顏色")
                        .Add("SizeSName", "貨品規格")
                        .Add("fGoodsamount", "數量")
                        .Add("GoodsPrice", "銷售價")
                        .Add("fSumMoney", "總金額")
                        .Add("fHouseId", "出貨點")
                        .Add("fRemark", "備註")
                    Case 2
                        .Add("ItemNo", "序號")
                        .Add("fDeliverDate", "送貨日期")
                        .Add("fTelphone", "客戶電話")
                        .Add("fConsigneeMan", "收貨人")
                        .Add("fAddressName", "客戶地址")
                        .Add("fRemark", "備注")
                        .Add("fOperaterMan", "建檔人員")
                        .Add("fOperaterDate", "建檔日期")
                        .Add("fOperaterComputer", "建檔電腦")
                        .Add("fUpdateMan", "更新人員")
                        .Add("fUpdateDate", "更新日期")
                        .Add("fUpdateComputer", "更新電腦")
                    Case 3
                        .Add("CheckA", "選擇")
                        .Add("fSaleOrdeNo", "銷售單號")
                        .Add("fCustomerId", "客戶編號")
                        .Add("fAecceptDate", "時間")
                        .Add("SiteNo", "站點")
                        .Add("fAddressName", "送貨地址")
                        .Add("fWriteNo", "手寫單號")
                        .Add("fCustomerName", "客戶名稱")
                        .Add("fSaleDate", "合同日期")

                        .Add("fDeliverDate", "送貨日期")
                        '.Add("fAecceptDate2", "結束時間")
                        .Add("fTelphone", "電話")
                        .Add("fConsigneeMan", "收貨人")
                        .Add("fEmployeeId", "銷售人員")
                        .Add("fDSIA", "即付定金")
                        .Add("fDSIB", "共收定金")
                        .Add("fBSI", "尾數")
                        .Add("fPayMode", "付款模式")
                        .Add("OutStoreHouse", "出貨點")
                        .Add("Ticket", "是否開票")
                        .Add("AreaName", "區域")
                        .Add("fRemark", "備注")
                    Case 4
                        .Add("HouseName", "倉庫")
                        .Add("Goodsamount", "數量")
                        .Add("fTypeMode", "類型")
                        '.Add("fDetail", "明細")

                    Case 5

                End Select

            End With
        Catch ex As Exception
            MessageBox.Show("Re_CaptionHash:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Hash
    End Function

    ''' <summary>
    ''' 設置是否可用
    ''' </summary>
    ''' <param name="bEnabled"></param>
    ''' <remarks></remarks>
    Private Sub SetControlEnabled(Optional ByVal bEnabled As Boolean = False)

        Dim bReadOnly As Boolean = Not bEnabled

        Me.txtfSaleOrdeNo_3_1.ReadOnly = bReadOnly
        Me.txtfWriteNo_3_1.ReadOnly = bReadOnly
        Me.txtfEmployeeId_3_1.ReadOnly = bReadOnly
        Me.txtfSaleDate_3_1.ReadOnly = bReadOnly
        Me.txtfCustomerName_3_1.ReadOnly = bReadOnly
        Me.txtPercentage_3_1.ReadOnly = bReadOnly
        Me.txtfDSIB_3_1.ReadOnly = bReadOnly
        Me.txtfDSIA_3_1.ReadOnly = bReadOnly
        Me.txtfBSI_3_1.ReadOnly = bReadOnly
        Me.txtfPayMode_3_1.ReadOnly = bReadOnly
        Me.txtfDeliverDate_3_1.ReadOnly = bReadOnly

    End Sub

    ''' <summary>
    ''' 返回庫存表
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Return_StoreDtab() As DataTable
        Dim Dtab As New DataTable
        With Dtab.Columns

            .Add("StoreHouse", GetType(System.String))
            .Add("HouseName", GetType(System.String))
            .Add("BarCode", GetType(System.String))
            .Add("GoodsName", GetType(System.String))
            '.Add("Goodsstatus", GetType(System.String))
            .Add("Goodsamount", GetType(System.Double))
            .Add("fType", GetType(System.String))
            .Add("fTypeMode", GetType(System.String))
        End With
        Return Dtab
    End Function

    ''' <summary>
    ''' 添加一個按鈕
    ''' </summary>
    ''' <param name="DGView"></param>
    ''' <remarks></remarks>
    Private Sub AddDataGridViewButton(ByRef DGView As DataGridView)
        Dim Column As DataGridViewButtonColumn = New DataGridViewButtonColumn()
        With Column
            .Name = "fDetail"
            .HeaderText = "明細"
            .Text = "..."
            .UseColumnTextForButtonValue = True
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
            .FlatStyle = FlatStyle.Standard
            .DefaultCellStyle.ForeColor = Color.Blue
        End With
        If DGView.Columns.Contains(Column.Name) = True Then
            DGView.Columns.Remove(Column.Name)
        End If
        DGView.Columns.Insert(DGView.Columns("fTypeMode").Index + 1, Column)
    End Sub

    ''' <summary>
    ''' 返回初如數據集
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function InitialDset() As DataSet
        Dim Dset As New DataSet
        Dim Sql As String = ""
        Sql &= " select * from  BSC_Dept where Isnull(fDefine,0)=1 order by Id " & vbCrLf
        Sql &= " select * from BSC_GoodsType where Isnull(fParentId,0)=0  " & vbCrLf
        Dset = Exec(Sql, E_ExecType.DataSet)
        Return Dset
    End Function

    Private Sub FillCombox(ByVal StoreDtab As DataTable)



        cbxTicket.Items.Clear()
        cbxTicket.Items.Add("是")
        cbxTicket.Items.Add("否")


        cbxTicket.Text = ""


        Dim Dtab As DataTable = BSC_AreaSetDtab.Copy
        cbx_AreaCode.DataSource = Dtab
        cbx_AreaCode.DisplayMember = "AreaName"
        cbx_AreaCode.ValueMember = "Id"
        'Dtab.DefaultView.RowFilter = "1<>1"

    End Sub

#End Region

#Region "TreeView Event"

    ''' <summary>
    ''' 加載樹結點
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeNode_1(ByRef Node As TreeNode)
        Try
            If Node.Nodes.Count > 1 OrElse Node.Nodes(0).Text.Trim <> "...".Trim Then Exit Sub
            Node.Nodes.Clear()
            Select Case Node.Level
                Case 0 ''加載線路
                    Dim DRow() As DataRow = Me.BSC_AreaSetDtab.Select("ParentId=0", "AreaCode asc")
                    For Each Row As DataRow In DRow
                        Dim NodeKey As String = Row("AreaCode") & ""
                        Dim NodeText As String = "(" & NodeKey & ")" & Row("AreaName") & ""
                        Dim Id As String = Row("Id") & ""
                        Dim TNode As TreeNode = Node.Nodes.Add(NodeKey, NodeText)
                        TNode.Tag = Id
                        LoadNodeImage(TNode, 1)
                    Next
                Case 1

            End Select

        Catch ex As Exception
            MessageBox.Show("Load_TreeNode:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 加載Tvw_2_1的結點
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeNode_2(ByRef Node As TreeNode)
        Try
            If Node.Nodes.Count > 1 OrElse Node.Nodes(0).Text.Trim <> "...".Trim Then Exit Sub
            Node.Nodes.Clear()
            Select Case Node.Level
                Case 0  ''加載路線
                    Dim KeyText As String = Node.Tag.ToString.Trim
                    For Each Tnode As TreeNode In Me.Tvw_1_1.Nodes(0).Nodes
                        If Tnode.Checked = True Then
                            Dim NodeKey As String = Tnode.Tag
                            Dim NodeText As String = Tnode.Text
                            Dim mNode As TreeNode = Node.Nodes.Add(NodeText)
                            mNode.Tag = KeyText & ":" & NodeKey
                            LoadNodeImage(mNode, 1)
                            Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId01,'')='" & NodeKey & "'")
                            If DRow.Length > 0 Then
                                mNode.Nodes.Add("...")
                            End If
                        End If
                    Next
                Case 1 ''加載送貨日期
                    Dim KeyText As String = Node.Tag.ToString.Trim
                    Dim fAreaId As String = KeyText.Split(":")(1).Trim

                    Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId01,'')='" & fAreaId & "'", "fDateKey Asc")
                    Dim Dic As New System.Collections.Specialized.StringDictionary

                    For Each Row As DataRow In DRow
                        Dim fSaleDate As String = Row("fSaleDate")
                        If Dic.ContainsKey(fSaleDate) = False Then
                            Dic.Add(fSaleDate, fSaleDate)
                            Dim NodeKey As String = KeyText & ":" & fSaleDate
                            Dim NodeText As String = fSaleDate
                            Dim Tnode As TreeNode = Node.Nodes.Add(NodeText)
                            Tnode.Tag = KeyText & ":" & fSaleDate
                            LoadNodeImage(Tnode, 2)
                            Tnode.Nodes.Add("...")
                        End If
                    Next

                Case 2  ''加載一級區域

                    Dim KeyText As String = Node.Tag.ToString.Trim
                    Dim ParentId As String = Node.Tag.ToString.Split(":")(1).Trim
                    Dim fSaleDate As String = KeyText.Split(":")(2).Trim

                    Dim DRow() As DataRow = Me.BSC_AreaSetDtab.Select("ParentId='" & ParentId & "'", "AreaNum asc")
                    For Each Row As DataRow In DRow
                        Dim Id As String = Row("Id") & ""
                        Dim NodeKey As String = Row("AreaCode") & ""
                        Dim NodeText As String = "(" & NodeKey & ")" & Row("AreaName") & ""
                        Dim fAreaId As String = ParentId & ":" & Id
                        NodeKey = KeyText & ":" & NodeKey
                        Dim Tnode As TreeNode = Node.Nodes.Add(NodeText)

                        Tnode.Tag = KeyText & ":" & Id
                        LoadNodeImage(Tnode, 3)
                        Dim PRow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId02,'')='" & Id & "' and fSaleDate='" & fSaleDate & "'")
                        'Dim MRow() As DataRow = Me.SaleOrdeACopy.Select("Isnull(fAreaId02,'')='" & Id & "' and fSaleDate='" & fSaleDate & "'")
                        'If PRow.Length > 0 AndAlso MRow.Length > 0 Then
                        '    Tnode.Nodes.Add("...")
                        'End If
                        If PRow.Length > 0 Then
                            Tnode.Nodes.Add("...")
                        End If
                    Next

                    ''只選定了路線
                    Dim DDRow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId02,'')='" & ParentId & "'  and fDateKey='" & fSaleDate & "'", "fDateKey Asc")
                    If DDRow.Length > 0 Then
                        Dim Tnode As TreeNode = Node.Nodes.Add("臨時節點")
                        Tnode.Tag = KeyText & ":" & ParentId
                        LoadNodeImage(Tnode, 3)
                        Dim MRow() As DataRow = Me.SaleOrdeACopy.Select("Isnull(fAreaId02,'')='" & ParentId & "' and fDateKey='" & fSaleDate & "'")
                        If MRow.Length > 0 Then
                            Tnode.Nodes.Add("...")
                        End If
                    End If

                Case 3 ''加載定單

                    Dim KeyText As String = Node.Tag.ToString.Trim
                    Dim ParentId As String = KeyText.Split(":")(1).Trim
                    Dim fSaleDate As String = KeyText.Split(":")(2).Trim

                    Dim fAreaId As String = KeyText.Split(":")(3).Trim

                    Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId02,'')='" & fAreaId & "' and fSaleDate='" & fSaleDate & "'", "fSaleDate asc")

                    For Each Row As DataRow In DRow
                        Dim fSaleOrdeNo As String = Row("fSaleOrdeNo") & ""
                        Dim fDestineDate As String = Row("fDestineDate") & ""
                        Dim fDeliverId As String = "＠" & Row("fDeliverId") & ""

                        'Dim MRow() As DataRow = Me.SaleOrdeACopy.Select("fDeliverId='" & fDeliverId.Replace("＠", "") & "'  and  fSaleOrdeNo='" & fSaleOrdeNo & "'")
                        'If MRow.Length > 0 Then
                        Dim Tnode As TreeNode = Node.Nodes.Add(fSaleOrdeNo)
                        Tnode.Tag = KeyText & ":" & fSaleOrdeNo & ":" & fDeliverId
                        If fDestineDate.Trim <> "" Then
                            Me.fCheckBool = True
                            Tnode.Checked = True
                            Me.fCheckBool = False
                        End If
                        LoadNodeImage(Tnode, 4)
                        'End If
                        ' ''刪除已加載的單號
                        'If MRow.Length > 0 Then
                        '    For Each ARow As DataRow In MRow
                        '        ARow.Delete()
                        '    Next
                        '    SaleOrdeACopy.AcceptChanges()
                        'End If
                    Next


                Case 4

            End Select

        Catch ex As Exception
            MessageBox.Show("Load_TreeNode_2:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 加載Tvw_3_1的結點
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeNode_3(ByRef Node As TreeNode)
        Try
            If Node.Nodes.Count > 1 OrElse Node.Nodes(0).Text.Trim <> "...".Trim Then Exit Sub
            Node.Nodes.Clear()
            Select Case Node.Level
                Case 0 ''加載路線
                    Dim KeyText As String = Node.Tag.ToString.Trim
                    For Each Tnode As TreeNode In Me.Tvw_1_1.Nodes(0).Nodes
                        If Tnode.Checked = True Then
                            Dim NodeKey As String = Tnode.Tag
                            Dim NodeText As String = Tnode.Text
                            Dim mNode As TreeNode = Node.Nodes.Add(NodeKey, NodeText)
                            mNode.Tag = KeyText & ":" & NodeKey
                            LoadNodeImage(mNode, 1)

                            Dim fAreaId As String = NodeKey

                            Dim AreaCode As String = ""
                            Dim SRow() As DataRow = Me.BSC_AreaSetDtab.Select("Id='" & fAreaId & "'")
                            If SRow.Length > 0 Then
                                AreaCode = SRow(0).Item("AreaCode") & ""
                            End If

                            Dim DRow() As DataRow = Me.Dtab_Truck.Select("ParentId='" & AreaCode & "'")
                            If DRow.Length > 0 Then
                                mNode.Nodes.Add("...")
                            End If

                        End If
                    Next

                Case 1 ''--後來加了車次具體那一倆車
                    ''加載車次
                    Dim KeyText As String = Node.Tag.ToString.Trim
                    Dim fAreaId As String = KeyText.Split(":")(1).Trim
                    Dim AreaCode As String = ""
                    Dim DRow() As DataRow = Me.BSC_AreaSetDtab.Select("Id='" & fAreaId & "'")
                    If DRow.Length > 0 Then
                        AreaCode = DRow(0).Item("AreaCode") & ""
                    End If

                    Dim PRow() As DataRow = Me.Dtab_Truck.Select("ParentId='" & AreaCode & "'")
                    For Each Row As DataRow In PRow
                        Dim TruckId As String = Row("TruckId") & ""
                        Dim TruckName As String = Row("TruckName") & ""
                        Dim Tnode As TreeNode = Node.Nodes.Add(TruckName)
                        Tnode.Tag = KeyText & ":" & TruckId
                        LoadNodeImage(Tnode, 1)
                        Dim SRow() As DataRow = Me.Set_Sal_SaleOrdeAP.Select("Isnull(fAreaId01,'')='" & fAreaId & "' and Isnull(fTructCode,'')='" & TruckId & "'  and Isnull(fDestineDate,'')<>''")
                        If SRow.Length > 0 Then
                            Tnode.Nodes.Add("...")
                        End If
                    Next


                Case 2 ''加載送貨日期

                    Dim KeyText As String = Node.Tag.ToString.Trim
                    Dim fAreaId As String = KeyText.Split(":")(1).Trim
                    Dim TruckId As String = KeyText.Split(":")(2).Trim

                    Dim DRow() As DataRow = Me.Set_Sal_SaleOrdeAP.Select("Isnull(fAreaId01,'')='" & fAreaId & "'  and isnull(fTructCode,'')='" & TruckId & "' and Isnull(fDestineDate,'')<>'' ", "fDestineDate Asc")
                    Dim Dic As New System.Collections.Specialized.StringDictionary

                    For Each Row As DataRow In DRow
                        Dim fDeliverDate As String = Row("fDestineDate")
                        If Dic.ContainsKey(fDeliverDate) = False Then
                            Dic.Add(fDeliverDate, fDeliverDate)
                            Dim NodeKey As String = KeyText & ":" & fDeliverDate
                            Dim NodeText As String = fDeliverDate
                            Dim Tnode As TreeNode = Node.Nodes.Add(NodeKey, NodeText)
                            Tnode.Tag = KeyText & ":" & fDeliverDate
                            LoadNodeImage(Tnode, 2)
                        End If
                    Next

                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("Load_TreeNode_3:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 加載Tvw_1_2結點
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeNode_1_2(ByRef Node As TreeNode)
        Try
            If Node.Nodes.Count > 1 OrElse Node.Nodes(0).Text.Trim <> "...".Trim Then Exit Sub
            Node.Nodes.Clear()

            Select Case Node.Level
                Case 0
                    For Each Row As DataRow In Me.GoodsTypeDtab.Rows
                        Dim fCode As String = Row("fCode") & ""
                        Dim fCName As String = Row("fCName") & ""
                        Dim NodeText As String = "(" & fCode & ")" & fCName
                        Dim Tnode As TreeNode = Node.Nodes.Add(fCode, NodeText)
                        Tnode.Tag = fCode
                        LoadNodeImage(Tnode, 1)
                    Next
                Case 1

                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("Load_TreeNode_1_2:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 結點選擇後
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub TreeNode_AfterSelect_2(ByVal Node As TreeNode)
        Try

            Select Case Node.Level
                Case 0, 1, 2, 3

                    FillDetail("", "")

                Case 4

                    Dim NodeTag As String = Node.Tag.ToString.Trim

                    Dim fSaleOrdeNo As String = NodeTag.Split(":")(4).Trim
                    Dim fDeliverId As String = NodeTag.Split(":")(5).Trim.Replace("＠", "")

                    FillDetail(fDeliverId, fSaleOrdeNo)

                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("TreeNode_AfterSelect:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 結點選擇後Tvw_3_1
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub TreeNode_AfterSelect_3(ByVal Node As TreeNode)
        Try

            ''記錄樹結點點擊事件
            fTreeSelectChanged = True

            Select Case Node.Level
                Case 0, 1, 2

                    FillDataGrid_3_1("", "", "")
                    FillDetail_3_1("", "")
                    If TypeOf Me.cbx_AreaCode.DataSource Is DataTable Then
                        Dim DtabArea As DataTable = DirectCast(Me.cbx_AreaCode.DataSource, DataTable)
                        DtabArea.DefaultView.RowFilter = "1<>1"
                    End If
                Case 3
                    Dim A() As String = Node.Tag.ToString.Split(":")
                    Dim DRow() As DataRow = Me.BSC_AreaSetDtab.Select("ID='" & A(1) & "'")
                    Dim fCarNo As String = ""
                    If DRow.Length > 0 Then
                        fCarNo = DRow(0).Item("AreaCode") & ""
                    End If
                    Dim fDeliverDate As String = A(3)
                    Dim fTructCode As String = A(2)

                    FillDataGrid_3_1(fCarNo, fDeliverDate, fTructCode)
                    If Me.DGV_3_1.SelectedRows.Count <= 0 Then
                        FillDetail_3_1("", "")
                    End If
                    If TypeOf Me.cbx_AreaCode.DataSource Is DataTable Then
                        Dim DtabArea As DataTable = DirectCast(Me.cbx_AreaCode.DataSource, DataTable)
                        DtabArea.DefaultView.RowFilter = "ParentId='" & A(1) & "'"
                        cbx_AreaCode.Text = ""
                    End If
                Case Else

            End Select

            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
            If Dtab.Rows.Count > 0 Then
                Me.txtfSaleOrdeNo_Filter.ReadOnly = False
                Me.cbx_AreaCode.Enabled = True
            Else
                Me.txtfSaleOrdeNo_Filter.ReadOnly = True
                Me.cbx_AreaCode.Enabled = False
            End If

        Catch ex As Exception
            MessageBox.Show("TreeNode_AfterSelect_3:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            fTreeSelectChanged = False
        End Try
    End Sub

    ''' <summary>
    ''' 選擇結點
    ''' </summary>
    ''' <param name="Node">結點</param>
    ''' <remarks>
    ''' AfterCheckBool 記錄狀態,不然會死循環
    ''' </remarks>
    Private Sub AfterCheckNode(ByRef Node As TreeNode)
        Try
            AfterCheckBool = True
            Dim CheckBool As Boolean = Node.Checked

            ''向下遍歷
            For Each Tnode As TreeNode In Node.Nodes
                CheckChildNode(Tnode, CheckBool)
            Next

            CheckParentNode(Node)
            AfterCheckBool = False
        Catch ex As Exception
            MessageBox.Show("AfterCheckNode:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

#End Region

#Region "填充數據"

    ''' <summary>
    ''' 填充明細
    ''' </summary>
    ''' <param name="fSaleOrdeNo"></param>
    ''' <remarks></remarks>
    Private Sub FillDetail(ByVal fDeliverId As String, ByVal fSaleOrdeNo As String)
        Try

            If Sal_SaleOrdeA.Columns.Contains("fSaleOrdeNo") = False Then GoTo A

            Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("fSaleOrdeNo='" & fSaleOrdeNo & "'  and Isnull(fDeliverId,'')='" & fDeliverId & "'")

            If DRow.Length > 0 Then
                Me.txtfSaleOrdeNo.Text = DRow(0).Item("fSaleOrdeNo") & ""
                Me.txtfWriteNo.Text = DRow(0).Item("fWriteNo") & ""
                Me.txtfEmployeeName.Text = DRow(0).Item("fEmployeeName") & ""
                txtfSaleDate.Text = DRow(0).Item("fSaleDate")
                Me.txtCnname.Text = DRow(0).Item("fCustomerId") & Space(4) & DRow(0).Item("Cnname")
                Me.txtReciveMan.Text = DRow(0).Item("LinkMan") & ""
                Me.txtfDeliverDate.Text = DRow(0).Item("fDeliverDate") & ""
                Me.txtDliverAddress.Text = DRow(0).Item("fDeliverAddress") & ""
                Me.txtCustomePhone.Text = DRow(0).Item("Telphone") & ""
                Me.txtfDeliverMode.Text = DRow(0).Item("fDeliverMode") & ""
                Me.txtPercentage.Text = fPercentage
                Me.TxtFTAmount.Text = DRow(0).Item("FTAmount") & ""
                Me.txtfDSIB.Text = DRow(0).Item("fDSIB") & ""
                Me.txtfDSIA.Text = DRow(0).Item("fDSIA") & ""
                'Me.txtfBSI.Text = DRow(0).Item("fBSI") & ""
                Me.txtfBSI.Text = DRow(0).Item("FTAmount") - DRow(0).Item("fDSIA") & ""
                Me.txtfPayMode.Text = DRow(0).Item("fPayMode") & ""
                Me.txtfRemark.Text = DRow(0).Item("fRemark")

                Me.txtfDestineDate.Text = DRow(0).Item("fDestineDate") & ""
                Me.txtTruckName.Text = DRow(0).Item("TruckName") & ""

            Else

A:

                Me.txtfSaleOrdeNo.Text = ""
                Me.txtfWriteNo.Text = ""
                Me.txtfEmployeeName.Text = ""

                Me.txtCnname.Text = ""
                Me.txtReciveMan.Text = ""

                Me.txtDliverAddress.Text = ""
                Me.txtCustomePhone.Text = ""
                Me.txtfDeliverMode.Text = ""
                Me.txtPercentage.Text = ""
                Me.txtfDSIB.Text = ""
                Me.txtfDSIA.Text = ""
                Me.TxtFTAmount.Text = ""
                Me.txtfBSI.Text = ""
                Me.txtfPayMode.Text = ""
                Me.txtfRemark.Text = ""

                txtfSaleDate.Text = ""
                Me.txtfDeliverDate.Text = ""
                Me.txtfDestineDate.Text = ""
                Me.txtTruckName.Text = ""
            End If

            txtfDestineRemark.Text = ""

            FillDataGridDetail(fDeliverId, fSaleOrdeNo, 2)

            Dim Dtab As DataTable = DirectCast(Me.DGV_2_3.DataSource, DataTable)
            If Not Dtab Is Nothing Then
                Dim PRow() As DataRow = Dtab.Select("", "ItemNo Desc")
                If PRow.Length > 0 Then
                    txtfDestineRemark.Text = PRow(0).Item("fRemark") & ""
                End If
            End If

        Catch ex As Exception
            MessageBox.Show("FillDetail:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    ''' <summary>
    ''' 填充網格明細
    ''' </summary>
    ''' <param name="fSaleOrdeNo"></param>
    ''' <remarks></remarks>
    Private Sub FillDataGridDetail(ByVal fDeliverId As String, ByVal fSaleOrdeNo As String, ByVal Index As Integer)
        Try
            Dim Sql As String = ""

            Select Case Index
                Case 2

                    'Sql &= " select  ItemNo,Replace(fGoodsBarCode,'*','') as fGoodsBarCode,b.ShortName as GoodsName," & vbCrLf
                    'Sql &= " (select ColorSName from BSC_ColorDefine c where c.ColorCode=b.Color) as ColorSName," & vbCrLf
                    'Sql &= " (select SizeSName from BSC_SizeDefine d where d.SizeCode=b.Spec) as SizeSName,a.fSumCount as fGoodsamount,b.Price as GoodsPrice,a.fSumMoney from Sal_SaleOrdeB a " & vbCrLf
                    'Sql &= " inner join BSC_Goods b on a.fGoodsBarCode=b.BarCode where fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf



                    If fDeliverId = "" Then

                        Dim TabA As String = System.Guid.NewGuid().ToString
                        Dim TabB As String = System.Guid.NewGuid().ToString



                        Sql &= " select  a.fSaleOrdeNo,ItemNo,Replace(fGoodsBarCode,'*','') as fGoodsBarCode,b.ShortName as GoodsName,SupperItem," & vbCrLf
                        Sql &= " (select ColorSName from BSC_ColorDefine c where c.ColorCode=b.Color) as ColorSName," & vbCrLf
                        Sql &= " (select SizeSName from BSC_SizeDefine d where d.SizeCode=b.Spec) as SizeSName,a.fSumCount as fGoodsamount,b.Price as GoodsPrice,a.fSumMoney," & vbCrLf
                        Sql &= " Case Isnull(fType,0) when 1 then '" & E_fTBackType.換貨.ToString & "' +' '+Rtrim(a.fRemark) when 2 then '" & E_fTBackType.換補件.ToString & "'+' '+Rtrim(a.fRemark) else a.fRemark end as fRemark " & vbCrLf
                        Sql &= " into [#" & TabA & "]  " & vbCrLf
                        Sql &= " from Sal_SaleOrdeB a " & vbCrLf
                        Sql &= " left join BSC_Goods b on a.fGoodsBarCode=b.BarCode where fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf

                        Sql &= "  select a.fSaleOrdeNo,a.ItemNo,Isnull(Sum(a.fTotal),0) as fTotal into[#" & TabB & "] from  dbo.DeliverGoodsInfo a " & vbCrLf
                        'Sql &= "  where  a.fSaleOrdeNo='" & fSaleOrdeNo & "' and a.fDeliverId+':'+a.fSaleOrdeNo in (select a.fDeliverId+':'+a.fSaleOrdeNo from  DeliverGoodsDetail a where fSaleOrdeNo='" & fSaleOrdeNo & "')" & vbCrLf
                        Sql &= "  where  a.fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf

                        Sql &= "  group  by a.fSaleOrdeNo,a.ItemNo " & vbCrLf

                        Sql &= "  update [#" & TabA & "] set fGoodsamount=fGoodsamount-b.fTotal from [#" & TabA & "] a inner join [#" & TabB & "] b on a.fSaleOrdeNo=b.fSaleOrdeNo and a.ItemNo=b.ItemNo" & vbCrLf

                        ''Sql &= " select * from [#" & TabA & "] where Isnull(fGoodsamount,0)>0" & vbCrLf
                        ''退換單不處理
                        Sql &= " if (select Isnull(flag,0) from Sal_SaleOrdeA where fSaleOrdeNo='" & fSaleOrdeNo & "')=0" & vbCrLf
                        Sql &= " begin" & vbCrLf
                        Sql &= " select * from [#" & TabA & "]  a where  fGoodsamount>0" & vbCrLf
                        Sql &= " End" & vbCrLf
                        Sql &= " Else" & vbCrLf
                        Sql &= " begin" & vbCrLf
                        Sql &= " select * from [#" & TabA & "]  a" & vbCrLf
                        Sql &= " end" & vbCrLf

                        Sql &= " drop Table [#" & TabA & "] " & vbCrLf
                        Sql &= " drop Table [#" & TabB & "] " & vbCrLf

                    Else
                        GoTo A
                    End If
                Case 3

A:

                    Sql &= Re_DeliverGoodsDetailInfo(fDeliverId, fSaleOrdeNo)

            End Select


            Sql &= " select fSaleOrdeNo,ItemNo,Convert(varchar(10),fDeliverDate,21) as fDeliverDate,fTelphone,fConsigneeMan,fAddressName,fRemark,fOperaterMan,fOperaterDate,fOperaterComputer," & vbCrLf
            Sql &= " fUpdateMan, fUpdateDate, fUpdateComputer"
            Sql &= " from Des_CustomerRecord  where fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf




            Dim Dtab As DataTable = Me.Return_StoreDtab()
            Dim Dset As New DataSet
            Dset = Exec(Sql, E_ExecType.DataSet)

            Select Case Index

                Case 2

                    Me.DGV_2_2.DataSource = Dtab
                    AddDataGridViewButton(DGV_2_2)
                    BindDataGridViewCaption(Me.DGV_2_2, Me.Re_CaptionHash(4))
                    FullFormatDataGridView(Me.DGV_2_2, False, False, False, True, False)
                    DGV_2_2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
                    DGV_2_2.SelectionMode = DataGridViewSelectionMode.CellSelect

                    Me.DGV_2_1.DataSource = Dset.Tables(0)
                    BindDataGridViewCaption(Me.DGV_2_1, Me.Re_CaptionHash(1))
                    FullFormatDataGridView(Me.DGV_2_1, False, False, False, True, False)

                    DGV_2_1.Columns("fGoodsamount").DefaultCellStyle.Format = "0.00"
                    DGV_2_1.Columns("fSumMoney").DefaultCellStyle.Format = "0.00"

                    Me.DGV_2_3.DataSource = Dset.Tables(1)
                    BindDataGridViewCaption(Me.DGV_2_3, Me.Re_CaptionHash(2))
                    FullFormatDataGridView(Me.DGV_2_3, False, False, False)
                    DGV_2_3.SelectionMode = DataGridViewSelectionMode.CellSelect

                Case 3

                    Me.DGView_3_4.DataSource = Dtab


                    BindDataGridViewCaption(Me.DGView_3_4, Me.Re_CaptionHash(4))
                    AddDataGridViewButton(DGView_3_4)

                    FullFormatDataGridView(Me.DGView_3_4, False, False, False, True, False)
                    DGView_3_4.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
                    DGView_3_4.SelectionMode = DataGridViewSelectionMode.CellSelect
                    fCellSelect = False
                    Me.DGView_3_2.DataSource = Dset.Tables(0)
                    BindDataGridViewCaption(Me.DGView_3_2, Me.Re_CaptionHash(1))
                    FullFormatDataGridView(Me.DGView_3_2, False, False, False, True, False)
                    DGView_3_2.AutoResizeColumns()
                    DGView_3_2.SelectionMode = DataGridViewSelectionMode.CellSelect
                    fCellSelect = True
                    'If Not DGView_3_2.CurrentCell Is Nothing Then
                    '    DGView_3_2.CurrentCell.Selected = True
                    'End If
                    DGView_3_2.Columns("fGoodsamount").DefaultCellStyle.Format = "0.00"
                    DGView_3_2.Columns("fSumMoney").DefaultCellStyle.Format = "0.00"

                    Me.DGView_3_3.DataSource = Dset.Tables(1)
                    BindDataGridViewCaption(Me.DGView_3_3, Me.Re_CaptionHash(2))
                    FullFormatDataGridView(Me.DGView_3_3, False, False, False)
                    DGView_3_3.SelectionMode = DataGridViewSelectionMode.CellSelect

                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("FillDataGridDetail:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 填充DGV_3_1網格
    ''' </summary>
    ''' <param name="fCarNo"></param>
    ''' <param name="fDeliverDate"></param>
    ''' <remarks></remarks>
    Private Sub FillDataGrid_3_1(Optional ByVal fCarNo As String = "", Optional ByVal fDeliverDate As String = "", Optional ByVal fTructCode As String = "")
        Try
            Dim Sql As String = " "

            Dim Dset As New DataSet
            Dim fDeliverId As String = ""
            If IsDate(fDeliverDate) = True Then
                fDeliverId = Format(CType(fDeliverDate, DateTime), "yyMMdd") & fCarNo.Trim & "-" & fTructCode
            End If
            Dim WhereExp As String = " where Isnull(b.fCarNo,'')='" & fCarNo & "' and Isnull(b.fDeliverDate,'')='" & fDeliverDate & "'  and Isnull(fTructCode,'')='" & fTructCode & "'" & vbCrLf
            Sql = Re_DeliverGoodsSaleSql(WhereExp)

            Sql &= " exec Computer_fVolumn '" & fDeliverId & "'" & vbCrLf
            Sql &= " select * from dbo.BSC_Truck where TruckId='" & fTructCode & "' " & vbCrLf

            Dset = Exec(Sql, E_ExecType.DataSet)

            'FillDataGridDetail("", "", 3)

            Me.DGV_3_1.DataSource = Dset.Tables(0)
            BindDataGridViewCaption(Me.DGV_3_1, Me.Re_CaptionHash(3))
            FullFormatDataGridView(Me.DGV_3_1, False, False, False)

            Dim fVolumn As Double = 0
            Dim fWeight As Double = 0
            Dim percentVolumn As Double = 0
            Dim percentWeight As Double = 0
            Dim fTotalVol As Double = 0
            Dim fTotalWgt As Double = 0


            If Dset.Tables(1).Rows.Count > 0 Then
                fVolumn = Val(Dset.Tables(1).Compute("Sum(fVolume)", "") & "")
                fWeight = Val(Dset.Tables(1).Compute("Sum(fWeight)", "") & "")
            End If
            If Dset.Tables(2).Rows.Count > 0 Then
                fTotalVol = Val(Dset.Tables(2).Rows(0).Item("fVolume") & "")
                fTotalWgt = Val(Dset.Tables(2).Rows(0).Item("fWeight") & "")
            End If

            If fTotalVol > 0 AndAlso fVolumn > 0 Then
                percentVolumn = Math.Round((fVolumn / fTotalVol) * 100%, 2)
            End If

            If fTotalWgt > 0 AndAlso fWeight > 0 Then
                percentWeight = Math.Round((fWeight / fTotalWgt) * 100%, 2)
            End If

            Me.lbWeight.Text = String.Format("V={0} PV={1}%;W={2} PW={3}%", fVolumn, percentVolumn, fWeight, percentWeight)
            If percentVolumn Or percentWeight > 100% Then
                Me.lbWeight.BackColor = Color.Red
            Else
                Me.lbWeight.BackColor = Color.White
            End If

        Catch ex As Exception
            MessageBox.Show("FillDataGrid_3_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 填充明細(Page3)
    ''' </summary>
    ''' <param name="fSaleOrdeNo"></param>
    ''' <remarks></remarks>
    Private Sub FillDetail_3_1(ByVal fDeliverId As String, ByVal fSaleOrdeNo As String)
        Try
            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)

            Dim Drow() As DataRow = Dtab.Select("fSaleOrdeNo='" & fSaleOrdeNo & "'")

            If Drow.Length > 0 Then
                Me.lbfDeliverId.Text = Drow(0).Item("fDeliverId") & ""
                Me.txtfSaleOrdeNo_3_1.Text = Drow(0).Item("fSaleOrdeNo") & ""
                Me.txtfWriteNo_3_1.Text = Drow(0).Item("fWriteNo") & ""
                Me.txtfEmployeeId_3_1.Text = Drow(0).Item("fEmployeeId") & ""
                Me.txtfSaleDate_3_1.Text = Drow(0).Item("fSaleDate") & ""
                Me.txtfCustomerName_3_1.Text = Drow(0).Item("fCustomerName") & ""
                Me.txtfConsigneeMan_3_1.Text = Drow(0).Item("fConsigneeMan") & ""
                Me.txtfDeliverDate_3_1.Text = Drow(0).Item("fDeliverDate") & ""
                Me.txtfAddressName_3_1.Text = Drow(0).Item("fAddressName") & ""
                Me.txtfTelphone_3_1.Text = Drow(0).Item("fTelphone") & ""
                Me.nudSiteNo_3_1.Value = Val(Drow(0).Item("SiteNo") & "")
                'Me.mtbfAecceptDate1_3_1.Text = Drow(0).Item("fAecceptDate1") & ""
                'Me.mtbfAecceptDate2_3_1.Text = Drow(0).Item("fAecceptDate2") & ""
                Me.txtfAecceptDate.Text = Drow(0).Item("fAecceptDate") & ""
                Me.cbxTicket.Text = ""
                Me.txtPercentage_3_1.Text = Me.fPercentage
                Me.txtfDSIB_3_1.Text = Drow(0).Item("fDSIB") & ""
                Me.txtfTAmount_3_1.Text = Drow(0).Item("fTAmount") & ""
                Me.txtfDSIA_3_1.Text = Drow(0).Item("fDSIA") & ""
                Me.txtfBSI_3_1.Text = Drow(0).Item("fBSI") & ""
                'Me.txtfBSI_3_1.Text = System.Convert.ToDouble(Drow(0).Item("fTAmount").ToString) - System.Convert.ToDouble(Drow(0).Item("fDSIA").ToString) & ""
                'Me.txtfBSI_3_1.Text = Me.txtfTAmount_3_1.Text - Me.txtfDSIA_3_1.Text & ""


                Me.txtfPayMode_3_1.Text = Drow(0).Item("fPayMode") & ""
                Me.txtfRemark_3_1.Text = Drow(0).Item("fRemark") & ""

                Me.cbxTicket.Text = Drow(0).Item("Ticket") & ""
            Else

                Me.lbfDeliverId.Text = ""
                Me.txtfSaleOrdeNo_3_1.Text = ""
                Me.txtfWriteNo_3_1.Text = ""
                Me.txtfEmployeeId_3_1.Text = ""
                Me.txtfSaleDate_3_1.Text = ""
                Me.txtfCustomerName_3_1.Text = ""
                Me.txtfConsigneeMan_3_1.Text = ""
                Me.txtfDeliverDate_3_1.Text = ""
                Me.txtfAddressName_3_1.Text = ""
                Me.txtfTelphone_3_1.Text = ""
                Me.nudSiteNo_3_1.Value = 0
                'Me.mtbfAecceptDate1_3_1.Text = ""
                'Me.mtbfAecceptDate2_3_1.Text = ""
                Me.txtfAecceptDate.Text = ""
                Me.cbxTicket.Text = ""
                Me.txtPercentage_3_1.Text = ""
                Me.txtfDSIB_3_1.Text = ""
                Me.txtfDSIA_3_1.Text = ""
                Me.txtfBSI_3_1.Text = ""
                Me.txtfPayMode_3_1.Text = ""
                Me.txtfRemark_3_1.Text = ""

                Me.cbxTicket.Text = ""
                'Me.lbWeight.Text = ""
            End If
        Catch ex As Exception
            MessageBox.Show("FillDetail_3_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 加載對應貨品的庫存
    ''' </summary>
    ''' <param name="DGView">網格</param>
    ''' <param name="BarCode">條碼</param>
    ''' <remarks></remarks>
    Private Sub FillStoreDataGridView(ByRef DGView As DataGridView, ByVal BarCode As String)
        Try

            Dim Sql As String = " Exec Re_BarCodeAmount_DG '" & BarCode & "' "
            Dim Dtab As DataTable = Exec(Sql, E_ExecType.DataTable)
            DGView.DataSource = Dtab
            AddDataGridViewButton(DGView)
            BindDataGridViewCaption(DGView, Me.Re_CaptionHash(4))
            FullFormatDataGridView(DGView, False, False, False, True, False)
            DGView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
            DGView.SelectionMode = DataGridViewSelectionMode.CellSelect
            DGView.Refresh()

        Catch ex As Exception
            MessageBox.Show("FillStoreDataGridView:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "ContextMenu Methods"


    ''' <summary>
    ''' 添加右鍵單擊事件
    ''' </summary>
    ''' <param name="IContexMenu"></param>
    ''' <remarks></remarks>
    Private Sub AddHandlers_IContexMenu(ByVal IContexMenu As ContextMenuStrip)
        Try
            For Each ICMenuItem As ToolStripMenuItem In IContexMenu.Items
                AddHandler ICMenuItem.Click, AddressOf IContextMenuItem_Click
            Next
        Catch ex As Exception
            MessageBox.Show("AddHandlers_IContexMenu:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 設置右鍵是否可用
    ''' </summary>
    ''' <param name="Index"></param>
    ''' <remarks></remarks>
    Private Sub ContextMenuEnabled(ByVal Index As Integer)
        Try
            Select Case Index
                Case 1

                    For Each CToolMenu As ToolStripMenuItem In Me.ContextMenuStrip1.Items
                        CToolMenu.Enabled = False
                        CToolMenu.Visible = False
                    Next
                    Me.ContextMenuStrip1.Items("tool_SaveStyle").Visible = True
                    Me.ContextMenuStrip1.Items("tool_SaveStyle").Enabled = False

                Case 2

                    Dim Node As TreeNode = Me.Tvw_2_1.SelectedNode

                    Dim DelBool As Boolean = False
                    If Me.DGV_2_3.RowCount > 0 Then
                        If Not Me.DGV_2_3.CurrentRow Is Nothing Then
                            Dim ItemNo As Integer = Val(DirectCast(Me.DGV_2_3.DataSource, DataTable).Compute("Max(ItemNo)", ""))
                            If Val(Me.DGV_2_3.CurrentRow.Cells("ItemNo").Value & "") = ItemNo Then
                                DelBool = True
                            End If
                        End If
                    End If

                    Dim fDeliverId As String = ""
                    Dim fSaleOrdeNo As String = ""

                    Dim BillBool As Boolean = True


                    Select Case Node.Level

                        Case 3    ''地址

                        Case 4
                            fDeliverId = Node.Tag.ToString.Trim.Split(":")(5).Replace("＠", "").Trim
                            fSaleOrdeNo = Node.Tag.ToString.Trim.Split(":")(4)
                            If fDeliverId.Trim <> "" Then
                                Dim BillStatus As String = ReturnBillStatus(fDeliverId, fSaleOrdeNo)
                                BillBool = IIf(BillStatus.Trim.ToLower = "A".ToLower OrElse BillStatus.Trim.ToLower = "C".ToLower, True, False)
                            End If
                        Case Else

                    End Select

                    Me.ContextMenuStrip1.Items("tool_SaveStyle").Visible = True
                    Me.ContextMenuStrip1.Items("tool_SaveStyle").Enabled = True


                    Me.ContextMenuStrip1.Items("tool_OK").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Edit").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Add").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Cancel").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Delete").Visible = True
                    Me.ContextMenuStrip1.Items("tool_SplitGoods").Visible = False
                    Me.ContextMenuStrip1.Items("tool_ChangArea").Visible = True

                    Me.ContextMenuStrip1.Items("tool_Operater").Visible = False
                    Me.ContextMenuStrip1.Items("tool_Save").Visible = False
                    Me.ContextMenuStrip1.Items("tool_Delete_3_1").Visible = False

                    Me.ContextMenuStrip1.Items("tool_OK").Enabled = (Not Node Is Nothing AndAlso Node.Level = 4) AndAlso BillBool
                    Me.ContextMenuStrip1.Items("tool_Edit").Enabled = (Not Node Is Nothing AndAlso Node.Level = 4) AndAlso DelBool
                    Me.ContextMenuStrip1.Items("tool_Add").Enabled = (Not Node Is Nothing AndAlso Node.Level = 4)
                    Me.ContextMenuStrip1.Items("tool_Cancel").Enabled = False
                    Me.ContextMenuStrip1.Items("tool_Delete").Enabled = (Not Node Is Nothing AndAlso Node.Level = 4) AndAlso DelBool
                    'Me.ContextMenuStrip1.Items("tool_ChangArea").Enabled = (Not Node Is Nothing AndAlso Node.Level = 4) AndAlso BillBool
                    Select Case Node.Level
                        Case 3
                            If Node.Nodes.Count > 0 Then
                                Me.ContextMenuStrip1.Items("tool_ChangArea").Enabled = True
                            Else
                                Me.ContextMenuStrip1.Items("tool_ChangArea").Enabled = False
                            End If
                        Case 4
                            Me.ContextMenuStrip1.Items("tool_ChangArea").Enabled = True
                        Case Else
                            Me.ContextMenuStrip1.Items("tool_ChangArea").Enabled = False
                    End Select

                Case 3

                    Dim Node As TreeNode = Me.Tvw_3_1.SelectedNode

                    Dim DelBool As Boolean = False
                    If Me.DGView_3_3.RowCount > 0 Then
                        If Not Me.DGView_3_3.CurrentRow Is Nothing Then
                            Dim ItemNo As Integer = Val(DirectCast(Me.DGView_3_3.DataSource, DataTable).Compute("Max(ItemNo)", ""))
                            If Val(Me.DGView_3_3.CurrentRow.Cells("ItemNo").Value & "") = ItemNo Then
                                DelBool = True
                            End If
                        End If
                    End If

                    Dim BillStatus As String = "A"
                    Dim fDeliverId As String = ""
                    Dim fSaleOrdeNo As String = ""
                    If Not Me.DGV_3_1.CurrentRow Is Nothing Then
                        fDeliverId = Me.DGV_3_1.CurrentRow.Cells("fDeliverId").Value & ""
                        fSaleOrdeNo = Me.DGV_3_1.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                        BillStatus = ReturnBillStatus(fDeliverId, fSaleOrdeNo)
                    End If

                    Dim BillBool As Boolean = IIf(BillStatus.Trim.ToLower = "A".ToLower OrElse BillStatus.Trim.ToLower = "C".ToLower, True, False)

                    Me.ContextMenuStrip1.Items("tool_SaveStyle").Visible = True
                    Me.ContextMenuStrip1.Items("tool_SaveStyle").Enabled = True

                    Me.ContextMenuStrip1.Items("tool_OK").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Edit").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Add").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Cancel").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Delete").Visible = True

                    Me.ContextMenuStrip1.Items("tool_Operater").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Save").Visible = True
                    Me.ContextMenuStrip1.Items("tool_Delete_3_1").Visible = True
                    Me.ContextMenuStrip1.Items("tool_SplitGoods").Visible = True
                    Me.ContextMenuStrip1.Items("tool_ChangArea").Visible = True

                    Me.ContextMenuStrip1.Items("tool_OK").Enabled = Not Me.DGV_3_1.CurrentRow Is Nothing AndAlso Action = IDServer.IDServer.ActionBtn.ActionHelp AndAlso BillBool

                    Me.ContextMenuStrip1.Items("tool_Add").Enabled = Not Me.DGV_3_1.CurrentRow Is Nothing

                    Me.ContextMenuStrip1.Items("tool_Cancel").Enabled = (Action = IDServer.IDServer.ActionBtn.ActionEdit)

                    Me.ContextMenuStrip1.Items("tool_Edit").Enabled = DelBool AndAlso Not Me.DGV_3_1.CurrentRow Is Nothing
                    Me.ContextMenuStrip1.Items("tool_Delete").Enabled = DelBool AndAlso Not Me.DGV_3_1.CurrentRow Is Nothing

                    Me.ContextMenuStrip1.Items("tool_Operater").Enabled = (Not Node Is Nothing) AndAlso (Node.Level = 3) AndAlso Action = IDServer.IDServer.ActionBtn.ActionHelp AndAlso BillBool
                    Me.ContextMenuStrip1.Items("tool_Save").Enabled = (Action = IDServer.IDServer.ActionBtn.ActionEdit)
                    Me.ContextMenuStrip1.Items("tool_Delete_3_1").Enabled = (Not Node Is Nothing) AndAlso (Node.Level = 3) AndAlso Action = IDServer.IDServer.ActionBtn.ActionHelp AndAlso BillBool
                    Me.ContextMenuStrip1.Items("tool_SplitGoods").Enabled = (Action = IDServer.IDServer.ActionBtn.ActionEdit)
                    Me.ContextMenuStrip1.Items("tool_ChangArea").Enabled = (Not Node Is Nothing) AndAlso (Node.Level = 3) AndAlso Action = IDServer.IDServer.ActionBtn.ActionHelp AndAlso BillBool

                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("ContextMenuEnabled:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 返回當前選擇Tabpage
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_SelectTabIndex() As Integer
        Dim Index As Integer = 0
        Select Case Me.TabControl1.SelectedTab.Name.ToLower
            Case "TabPage1".ToLower
                Index = 1
            Case "TabPage2".ToLower
                Index = 2
            Case "TabPage3".ToLower
                Index = 3
            Case "TabPage4".ToLower
                Index = 4
            Case "TabPage5".ToLower
                Index = 5
            Case Else

        End Select
        Return Index
    End Function

    ''' <summary>
    ''' 右鍵單擊事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub IContextMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            Dim ICMenuItem As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)

            Dim TabIndex As Integer = Me.Re_SelectTabIndex()

            Select Case ICMenuItem.Name.ToLower

                Case Me.tool_OK.Name.ToLower ''預排

                    Me.Tool_OK_Click(TabIndex)

                Case Me.tool_Add.Name.ToLower ''新增約客記錄

                    Me.Tool_Add_Click(TabIndex)

                Case Me.tool_Edit.Name.ToLower ''修改約客記錄

                    Me.Tool_Edit_Click(TabIndex)

                Case Me.tool_Delete.Name.ToLower ''刪除約客記錄

                    Select Case TabIndex
                        Case 2
                            Tool_Delete_Click(Me.DGV_2_3)
                        Case 3
                            Tool_Delete_Click(Me.DGView_3_3)
                        Case Else

                    End Select


                Case Me.tool_Operater.Name.ToLower ''編輯

                    Tool_Operater_Click()

                Case Me.tool_Save.Name.ToLower

                    Tool_Save_Click()

                Case Me.tool_Cancel.Name.ToLower ''取消

                    Tool_Cancel_Click(TabIndex)

                Case Me.tool_Delete_3_1.Name.ToLower

                    Tool_Delete_3_1_Click()

                Case Me.tool_SplitGoods.Name.ToLower

                    Tool_SplitGoods_Click()

                Case Me.tool_ChangArea.Name.ToLower

                    Tool_ChangArea_Click(TabIndex)

                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("IContextMenuItem_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 預排
    ''' </summary>
    ''' <param name="TabIndex"></param>
    ''' <remarks></remarks>
    Private Sub Tool_OK_Click(ByVal TabIndex As Integer)
        Try
            Dim Node As New TreeNode
            Select Case TabIndex

                Case 1

                Case 2
                    Node = Me.Tvw_2_1.SelectedNode

                    Dim frm As New Frm_DestineInput
                    frm.Text = "預排"
                    frm.Set_Index = 1
                    frm.StartPosition = FormStartPosition.CenterScreen
                    frm.txtAddressName.Text = Me.txtDliverAddress.Text.Trim
                    frm.txtfConsigneeMan.Text = Me.txtReciveMan.Text.Trim
                    frm.txtfTelphone.Text = Me.txtCustomePhone.Text.Trim
                    frm.dtpfDestineDate.Text = IIf(IsDate(Me.txtfDestineDate.Text) = True, Me.txtfDestineDate.Text, Me.txtfDeliverDate.Text)
                    frm.txtfRemark.Text = Me.txtfRemark.Text.Trim
                    frm.Set_fDeliverDate = Me.txtfDestineDate.Text.Trim
                    Dim fAreaCode As String = ""
                    Dim fCarName As String = ""

                    Dim fAreaId As String = Node.Tag.ToString.Split(":")(1).Trim
                    Dim ARow() As DataRow = Me.BSC_AreaSetDtab.Select("Id='" & fAreaId & "'")
                    If ARow.Length > 0 Then
                        fAreaCode = ARow(0).Item("AreaCode") & ""
                        fCarName = ARow(0).Item("AreaName") & ""
                    End If
                    frm.Set_fAreaCode = fAreaCode

                    If frm.ShowDialog = DialogResult.OK Then

                        If Not Node Is Nothing AndAlso Node.Level = 4 Then

                            Dim fTructCode As String = ""
                            Dim fTructName As String = frm.cbxfTruck.Text.Trim & ""
                            If Not frm.cbxfTruck.SelectedValue Is Nothing Then
                                fTructCode = frm.cbxfTruck.SelectedValue & ""
                            End If

                            Dim A() As String = Node.Tag.ToString.Split(":")

                            Dim Id As String = Node.Tag.ToString.Split(":")(1)
                            Dim fDeliverDate As String = ""
                            If frm.CheckBox1.Checked = True Then
                                fDeliverDate = frm.dtpfDestineDate.Text.Trim & ""
                            End If
                            Dim AreaCode As String = ""
                            Dim DRow() As DataRow = BSC_AreaSetDtab.Select("Id='" & Id & "'")
                            If DRow.Length > 0 Then
                                AreaCode = DRow(0).Item("AreaCode")
                            End If
                            Dim fDeliverId As String = Format(CType(fDeliverDate, Date), "yyMMdd") & AreaCode & "-" & fTructCode
                            Dim fOldDeliverId As String = ""

                            If A.Length = 6 Then
                                fOldDeliverId = A(5).ToString.Replace("＠", "")
                            End If
                            Dim Status As String = ""

                            Dim EditBool As Boolean = IsExistsfDeliverId(AreaCode, fDeliverDate, Status, fTructCode)

                            If Status.ToLower = "B".ToLower OrElse Status.ToLower = "F".ToLower Then
                                MessageBox.Show("排程單" & fDeliverId & "已" & Status.Replace("B", "核准").Replace("F", "結案") & "不能再排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                                Exit Sub
                            End If

                            Dim Sql As String = ""

                            Dim fSaleOrdeNo As String = Node.Tag.ToString.Split(":")(4).Trim
                            Dim fAddressName As String = frm.txtAddressName.Text.Trim
                            Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                            Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                            Dim fRemark As String = frm.txtfRemark.Text.Trim


                            Dim fTruckName As String = frm.cbxfTruck.Text.Trim & ""


                            Dim IsUnionBool As Boolean = False

                            Dim Bool As Boolean = Tool_YPSaveData(fDeliverId, fOldDeliverId, fSaleOrdeNo, AreaCode, fDeliverDate, fAddressName, fConsigneeMan, fTelphone, fRemark, fTructCode, Me.DGV_2_1, EditBool, 2, IsUnionBool, "", fCarName, fTruckName)

                            UpdateData(fAddressName, fConsigneeMan, fTelphone, fDeliverDate, fRemark, fSaleOrdeNo, fDeliverId, fOldDeliverId, fTructName)

                            ''更新結點
                            A(5) = "＠" & fDeliverId
                            Dim NodeTag As New System.Text.StringBuilder
                            For Each Value As String In A
                                If NodeTag.ToString <> "" Then
                                    NodeTag.Append(":")
                                End If
                                NodeTag.Append(Value)
                            Next
                            Node.Tag = NodeTag.ToString

                            Me.fCheckBool = True
                            Node.Checked = True
                            Me.fCheckBool = False

                            MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

                        End If
                    End If

                Case 3

                    Node = Me.Tvw_3_1.SelectedNode

                    Dim frm As New Frm_DestineInput
                    frm.Text = "預排"
                    frm.Set_Index = 1


                    frm.StartPosition = FormStartPosition.CenterScreen
                    frm.txtAddressName.Text = Me.txtfAddressName_3_1.Text.Trim
                    frm.txtfConsigneeMan.Text = Me.txtfConsigneeMan_3_1.Text.Trim
                    frm.txtfTelphone.Text = Me.txtfTelphone_3_1.Text.Trim
                    frm.txtfRemark.Text = Me.txtfRemark_3_1.Text.Trim
                    frm.Set_fDeliverDate = Me.txtfDestineDate.Text.Trim
                    Dim fAreaId As String = Node.Tag.ToString.Split(":")(1).Trim
                    Dim fAreaCode As String = ""
                    Dim fCarName As String = ""
                    Dim ARow() As DataRow = Me.BSC_AreaSetDtab.Select("Id='" & fAreaId & "'")
                    If ARow.Length > 0 Then
                        fAreaCode = ARow(0).Item("AreaCode") & ""
                        fCarName = ARow(0).Item("AreaName") & ""
                    End If

                    frm.Set_fAreaCode = fAreaCode
                    If frm.ShowDialog = DialogResult.OK Then


                        If Not Node Is Nothing Then



                            Dim Id As String = Node.Tag.ToString.Split(":")(1)
                            Dim fDeliverDate As String = ""
                            If frm.CheckBox1.Checked = True Then
                                fDeliverDate = frm.dtpfDestineDate.Text.Trim & ""
                            End If
                            Dim AreaCode As String = ""
                            Dim DRow() As DataRow = BSC_AreaSetDtab.Select("Id='" & Id & "'")
                            If DRow.Length > 0 Then
                                AreaCode = DRow(0).Item("AreaCode")
                                fCarName = ARow(0).Item("AreaName") & ""
                            End If
                            Dim fTructCode As String = ""
                            Dim fTruckName As String = frm.cbxfTruck.Text & ""
                            If Not frm.cbxfTruck.SelectedValue Is Nothing Then
                                fTructCode = frm.cbxfTruck.SelectedValue & ""
                            End If


                            Dim fDeliverId As String = Format(CType(fDeliverDate, DateTime), "yyMMdd") & AreaCode & "-" & fTructCode

                            Dim fOldDeliverId As String = ""
                            If Not Me.DGV_3_1.CurrentRow Is Nothing Then
                                fOldDeliverId = Me.DGV_3_1.CurrentRow.Cells("fDeliverId").Value & ""
                            Else
                                fOldDeliverId = ""
                            End If
                            Dim Status As String = ""

                            Dim EditBool As Boolean = IsExistsfDeliverId(AreaCode, fDeliverDate, Status, fTructCode)


                            If Status.ToLower = "B".ToLower OrElse Status.ToLower = "F".ToLower Then
                                MessageBox.Show("排程單" & fDeliverId & "已" & Status.Replace("B", "核准").Replace("F", "結案") & "不能再排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                                Exit Sub
                            End If

                            Dim Sql As String = ""

                            Dim fSaleOrdeNo As String = Me.txtfSaleOrdeNo_3_1.Text.Trim
                            Dim fAddressName As String = frm.txtAddressName.Text.Trim
                            Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                            Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                            Dim fRemark As String = frm.txtfRemark.Text.Trim


                            'Dim fTruckName As String = ""


                            Dim IsUnionBool As Boolean = False
                            Dim Bool As Boolean = Tool_YPSaveData(fDeliverId, fOldDeliverId, fSaleOrdeNo, AreaCode, fDeliverDate, fAddressName, fConsigneeMan, fTelphone, fRemark, fTructCode, Me.DGView_3_2, EditBool, 2, IsUnionBool, "", fCarName, fTruckName)


                            UpdateData(fAddressName, fConsigneeMan, fTelphone, fDeliverDate, fRemark, fSaleOrdeNo, fDeliverId, fOldDeliverId, fTruckName, False)
                            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
                            Dim PRow() As DataRow = Dtab.Select("fSaleOrdeNo='" & fSaleOrdeNo & "' and Isnull(fDeliverId,'')='" & fOldDeliverId & "'")
                            For Each Row As DataRow In PRow
                                Row.Delete()
                            Next

                            Dtab.AcceptChanges()
                            Me.DGV_3_1.Update()
                            Me.DGV_3_1.Refresh()
                            MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        End If
                    End If

                Case Else


            End Select

        Catch ex As Exception
            MessageBox.Show("Tool_OK_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 新增約客記錄
    ''' </summary>
    ''' <param name="TabIndex"></param>
    ''' <remarks></remarks>
    Private Sub Tool_Add_Click(ByVal TabIndex As Integer)
        Try
            Dim Node As New TreeNode

            Select Case TabIndex

                Case 1

                Case 2

                    Node = Me.Tvw_2_1.SelectedNode

                    Dim frm As New Frm_DestineInput
                    frm.Text = "溝通記錄"
                    frm.Set_Index = 2
                    frm.StartPosition = FormStartPosition.CenterScreen
                    frm.txtAddressName.Text = Me.txtDliverAddress.Text.Trim
                    frm.txtfConsigneeMan.Text = Me.txtReciveMan.Text.Trim
                    frm.txtfTelphone.Text = Me.txtCustomePhone.Text.Trim
                    If IsDate(txtfDestineDate.Text) = True Then
                        frm.dtpfDestineDate.Text = txtfDestineDate.Text
                    ElseIf IsDate(txtfDeliverDate.Text) = True Then
                        frm.dtpfDestineDate.Text = txtfDeliverDate.Text
                    End If
                    If frm.ShowDialog = DialogResult.OK Then

                        Dim Sql As String = ""


                        Dim fSaleOrdeNo As String = Node.Tag.ToString.Split(":")(4).Trim
                        Dim fAddressName As String = frm.txtAddressName.Text.Trim
                        Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                        Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                        Dim fRemark As String = frm.txtfRemark.Text.Trim
                        Dim fDeliverDate As String = ""
                        If frm.CheckBox1.Checked = True Then
                            fDeliverDate = frm.dtpfDestineDate.Text.Trim & ""
                        End If
                        Dim OperatePerson As String = PubUserName
                        Dim OperateDate As String = Format(Me.fDateValue, "yyyy-MM-dd")
                        Dim OPerateComputer As String = My.Computer.Name

                        Sql &= " Declare @ItemNo Int" & vbCrLf
                        Sql &= " select @ItemNo=Isnull(Max(ItemNo),0)+1 from dbo.Des_CustomerRecord where fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf
                        Sql &= " Insert Into Des_CustomerRecord(fSaleOrdeNo,ItemNo,fDeliverDate,fTelphone,fConsigneeMan,fAddressName,fRemark,fOperaterMan,fOperaterDate,fOperaterComputer)" & vbCrLf
                        Sql &= " values('" & fSaleOrdeNo & "',@ItemNo," & IIf(fDeliverDate.Trim = "-  -", "Null", "'" & fDeliverDate & "'") & ",'" & fTelphone & "','" & fConsigneeMan & "','" & fAddressName & "','" & fRemark & "','" & OperatePerson & "',Getdate(),'" & OPerateComputer & "')" & vbCrLf
                        Sql &= " select @ItemNo" & vbCrLf

                        Dim ItemNo As Int16 = Val(Exec(Sql, E_ExecType.ExecuteScalar) & "")

                        Dim Dtab As DataTable = DirectCast(Me.DGV_2_3.DataSource, DataTable)
                        Dim Row As DataRow = Dtab.NewRow
                        Row("fSaleOrdeNo") = fSaleOrdeNo
                        Row("ItemNo") = ItemNo
                        Row("fDeliverDate") = IIf(fDeliverDate.Trim = "-  -", "", fDeliverDate)
                        Row("fTelphone") = fTelphone
                        Row("fConsigneeMan") = fConsigneeMan
                        Row("fAddressName") = fAddressName
                        Row("fRemark") = fRemark
                        Row("fOperaterMan") = OperatePerson
                        Row("fOperaterDate") = OperateDate
                        Row("fOperaterComputer") = OPerateComputer
                        Dtab.Rows.Add(Row)
                        Dtab.AcceptChanges()
                        Me.DGV_2_3.Update()
                        Me.txtfDestineRemark.Text = fRemark
                        MessageBox.Show(My.resources.Addsuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If
                Case 3

                    Node = Me.Tvw_3_1.SelectedNode

                    Dim frm As New Frm_DestineInput
                    frm.Text = "溝通記錄"
                    frm.Set_Index = 2
                    frm.StartPosition = FormStartPosition.CenterScreen
                    frm.txtAddressName.Text = Me.txtfAddressName_3_1.Text
                    frm.txtfConsigneeMan.Text = Me.txtfConsigneeMan_3_1.Text
                    frm.txtfTelphone.Text = Me.txtfTelphone_3_1.Text
                    If IsDate(txtfDeliverDate_3_1.Text) = True Then
                        frm.dtpfDestineDate.Text = txtfDeliverDate_3_1.Text
                    End If
                    If frm.ShowDialog = DialogResult.OK Then

                        Dim Sql As String = ""

                        Dim fSaleOrdeNo As String = Me.txtfSaleOrdeNo_3_1.Text.Trim
                        Dim fAddressName As String = frm.txtAddressName.Text.Trim
                        Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                        Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                        Dim fRemark As String = frm.txtfRemark.Text.Trim
                        Dim fDeliverDate As String = ""
                        If frm.CheckBox1.Checked = True Then
                            fDeliverDate = frm.dtpfDestineDate.Text.Trim
                        End If
                        Dim OperatePerson As String = PubUserName
                        Dim OperateDate As String = Format(Me.fDateValue, "yyyy-MM-dd")
                        Dim OPerateComputer As String = My.Computer.Name

                        Sql &= " Declare @ItemNo Int" & vbCrLf
                        Sql &= " select @ItemNo=Isnull(Max(ItemNo),0)+1 from dbo.Des_CustomerRecord where fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf
                        Sql &= " Insert Into Des_CustomerRecord(fSaleOrdeNo,ItemNo,fDeliverDate,fTelphone,fConsigneeMan,fAddressName,fRemark,fOperaterMan,fOperaterDate,fOperaterComputer)" & vbCrLf
                        Sql &= " values('" & fSaleOrdeNo & "',@ItemNo," & IIf(fDeliverDate.Trim = "-  -", "Null", "'" & fDeliverDate & "'") & ",'" & fTelphone & "','" & fConsigneeMan & "','" & fAddressName & "','" & fRemark & "','" & OperatePerson & "',Getdate(),'" & OPerateComputer & "')" & vbCrLf
                        Sql &= " select @ItemNo" & vbCrLf

                        Dim ItemNo As Int16 = Val(Exec(Sql, E_ExecType.ExecuteScalar) & "")

                        Dim Dtab As DataTable = DirectCast(Me.DGView_3_3.DataSource, DataTable)
                        Dim Row As DataRow = Dtab.NewRow
                        Row("fSaleOrdeNo") = fSaleOrdeNo
                        Row("ItemNo") = ItemNo
                        Row("fDeliverDate") = IIf(fDeliverDate.Trim = "-  -", "", fDeliverDate)
                        Row("fTelphone") = fTelphone
                        Row("fConsigneeMan") = fConsigneeMan
                        Row("fAddressName") = fAddressName
                        Row("fRemark") = fRemark
                        Row("fOperaterMan") = OperatePerson
                        Row("fOperaterDate") = OperateDate
                        Row("fOperaterComputer") = OPerateComputer
                        Dtab.Rows.Add(Row)
                        Dtab.AcceptChanges()
                        Me.DGView_3_3.Update()

                        MessageBox.Show(My.resources.Addsuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

                    End If
                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("Tool_Add_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 修改約客記錄
    ''' </summary>
    ''' <param name="TabIndex"></param>
    ''' <remarks></remarks>
    Private Sub Tool_Edit_Click(ByVal TabIndex As Integer)
        Try
            Dim Node As New TreeNode

            Select Case TabIndex

                Case 1

                Case 2

                    Node = Me.Tvw_2_1.SelectedNode


                    Dim frm As New Frm_DestineInput
                    frm.Text = "溝通記錄"
                    frm.Set_Index = 2
                    frm.StartPosition = FormStartPosition.CenterScreen

                    If Not Me.DGV_2_3.CurrentRow Is Nothing Then

                        If IsDate(Me.DGV_2_3.CurrentRow.Cells("fDeliverDate").Value & "") = True Then
                            frm.dtpfDestineDate.Text = Me.DGV_2_3.CurrentRow.Cells("fDeliverDate").Value
                        Else
                            frm.CheckBox1.Checked = False
                        End If
                        frm.txtfConsigneeMan.Text = Me.DGV_2_3.CurrentRow.Cells("fConsigneeMan").Value & ""
                        frm.txtfTelphone.Text = Me.DGV_2_3.CurrentRow.Cells("fTelphone").Value & ""
                        frm.txtfRemark.Text = Me.DGV_2_3.CurrentRow.Cells("fRemark").Value & ""
                        frm.txtAddressName.Text = Me.DGV_2_3.CurrentRow.Cells("fAddressName").Value & ""

                    End If

                    If frm.ShowDialog = DialogResult.OK Then

                        Dim fSaleOrdeNo As String = Node.Tag.ToString.Split(":")(4).Trim
                        Dim fAddressName As String = frm.txtAddressName.Text.Trim
                        Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                        Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                        Dim fRemark As String = frm.txtfRemark.Text.Trim
                        Dim fDeliverDate As String = ""
                        If frm.CheckBox1.Checked = True Then
                            fDeliverDate = frm.dtpfDestineDate.Text.Trim
                        End If
                        Dim OperatePerson As String = PubUserName
                        Dim OperateDate As String = Format(Me.fDateValue, "yyyy-MM-dd")
                        Dim OPerateComputer As String = My.Computer.Name
                        Dim ItemNo As Integer = Val(Me.DGV_2_3.CurrentRow.Cells("ItemNo").Value & "")

                        Dim Sql As String = ""
                        Sql &= "  Update Des_CustomerRecord set fSaleOrdeNo='" & fSaleOrdeNo & "',ItemNo='" & ItemNo & "',fDeliverDate=" & IIf(fDeliverDate.Trim = "-  -", "Null", "'" & fDeliverDate & "'") & ",fTelphone='" & fTelphone & "',fConsigneeMan='" & fConsigneeMan & "',fAddressName='" & fAddressName & "',fRemark='" & fRemark & "',fUpdateMan='" & OperatePerson & "',fUpdateDate=Getdate(),fUpdateComputer='" & OPerateComputer & "'"
                        Sql &= "  where  fSaleOrdeNo='" & fSaleOrdeNo & "' and ItemNo=" & ItemNo & ""

                        Exec(Sql, E_ExecType.ExecuteNonQuery)
                        Dim Dtab As DataTable = DirectCast(Me.DGV_2_3.DataSource, DataTable)

                        Dim DRow() As DataRow = Dtab.Select("fSaleOrdeNo='" & fSaleOrdeNo & "'  and ItemNo='" & ItemNo & "'")

                        If DRow.Length > 0 Then

                            DRow(0).Item("fDeliverDate") = IIf(fDeliverDate.Trim = "-  -", "", fDeliverDate)
                            DRow(0).Item("fTelphone") = fTelphone
                            DRow(0).Item("fConsigneeMan") = fConsigneeMan
                            DRow(0).Item("fAddressName") = fAddressName
                            DRow(0).Item("fRemark") = fRemark
                            DRow(0).Item("fUpdateMan") = OperatePerson
                            DRow(0).Item("fUpdateDate") = OperateDate
                            DRow(0).Item("fUpdateComputer") = OPerateComputer

                        End If
                        Me.txtfDestineRemark.Text = fRemark
                        Dtab.AcceptChanges()
                        Me.DGV_2_3.Update()

                        txtfDestineRemark.Text = ""
                        If Not Dtab Is Nothing Then
                            Dim PRow() As DataRow = Dtab.Select("", "ItemNo Desc")
                            If PRow.Length > 0 Then
                                txtfDestineRemark.Text = PRow(0).Item("fRemark") & ""
                            End If
                        End If
                        MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If

                Case 3

                    Dim frm As New Frm_DestineInput
                    frm.Text = "溝通記錄"
                    frm.Set_Index = 2


                    If Not Me.DGView_3_3.CurrentRow Is Nothing Then

                        If IsDate(Me.DGView_3_3.CurrentRow.Cells("fDeliverDate").Value & "") = True Then
                            frm.dtpfDestineDate.Text = Me.DGView_3_3.CurrentRow.Cells("fDeliverDate").Value
                        Else
                            frm.CheckBox1.Checked = False
                        End If

                        frm.txtfConsigneeMan.Text = Me.DGView_3_3.CurrentRow.Cells("fConsigneeMan").Value & ""
                        frm.txtfTelphone.Text = Me.DGView_3_3.CurrentRow.Cells("fTelphone").Value & ""
                        frm.txtfRemark.Text = Me.DGView_3_3.CurrentRow.Cells("fRemark").Value & ""
                        frm.txtAddressName.Text = Me.DGView_3_3.CurrentRow.Cells("fAddressName").Value & ""

                    End If

                    frm.StartPosition = FormStartPosition.CenterScreen
                    If frm.ShowDialog = DialogResult.OK Then

                        Dim fSaleOrdeNo As String = Me.txtfSaleOrdeNo_3_1.Text.Trim
                        Dim fAddressName As String = frm.txtAddressName.Text.Trim
                        Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                        Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                        Dim fRemark As String = frm.txtfRemark.Text.Trim
                        Dim fDeliverDate As String = ""
                        If frm.CheckBox1.Checked = True Then
                            fDeliverDate = frm.dtpfDestineDate.Text.Trim
                        End If
                        Dim OperatePerson As String = PubUserName
                        Dim OperateDate As String = Format(Me.fDateValue, "yyyy-MM-dd")
                        Dim OPerateComputer As String = My.Computer.Name
                        Dim ItemNo As Integer = Val(Me.DGView_3_3.CurrentRow.Cells("ItemNo").Value & "")

                        Dim Dtab As DataTable = DirectCast(Me.DGView_3_3.DataSource, DataTable)

                        Dim Sql As String = ""
                        Sql &= "  Update Des_CustomerRecord set fSaleOrdeNo='" & fSaleOrdeNo & "',ItemNo='" & ItemNo & "',fDeliverDate=" & IIf(fDeliverDate.Trim = "-  -", "Null", "'" & fDeliverDate & "'") & ",fTelphone='" & fTelphone & "',fConsigneeMan='" & fConsigneeMan & "',fAddressName='" & fAddressName & "',fRemark='" & fRemark & "',fUpdateMan='" & OperatePerson & "',fUpdateDate=Getdate(),fUpdateComputer='" & OPerateComputer & "'"
                        Sql &= "  where  fSaleOrdeNo='" & fSaleOrdeNo & "' and ItemNo=" & ItemNo & ""

                        Exec(Sql, E_ExecType.ExecuteNonQuery)

                        Dim DRow() As DataRow = Dtab.Select("fSaleOrdeNo='" & fSaleOrdeNo & "'  and ItemNo='" & ItemNo & "'")

                        If DRow.Length > 0 Then

                            DRow(0).Item("fDeliverDate") = IIf(fDeliverDate.Trim = "-  -", "", fDeliverDate)
                            DRow(0).Item("fTelphone") = fTelphone
                            DRow(0).Item("fConsigneeMan") = fConsigneeMan
                            DRow(0).Item("fAddressName") = fAddressName
                            DRow(0).Item("fRemark") = fRemark
                            DRow(0).Item("fUpdateMan") = OperatePerson
                            DRow(0).Item("fUpdateDate") = OperateDate
                            DRow(0).Item("fUpdateComputer") = OPerateComputer

                        End If

                        Dtab.AcceptChanges()
                        Me.DGView_3_3.Update()
                        MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If

                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("Tool_Edit_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 編輯
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Tool_Operater_Click()
        Try

            setControlsbEnabled(New Control() {Me.TabControl3.TabPages(0)}, True)
            SetControlEnabled(False)
            Dim Hash As New Hashtable
            Hash.Add("fHouseId", "fHouseId")
            DGView_3_2.ReadOnly = False
            SetDataGridViewEnabledColumn(Me.DGView_3_2, Hash)
            Me.Action = IDServer.IDServer.ActionBtn.ActionEdit
            Me.btnPrevious.Enabled = False
            Me.btnNext.Enabled = False
            Me.IsEditMode = False
            ''網格不可以用只能修改一行
            Me.DGV_3_1.Enabled = False
            Me.txtfSaleOrdeNo_Filter.ReadOnly = True
            Me.cbx_AreaCode.Enabled = False
        Catch ex As Exception
            MessageBox.Show("Tool_Operater_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 保存
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Tool_Save_Click()
        Try

            If Validated_3_1() = False Then Exit Sub
            SaveData_3_1()

        Catch ex As Exception
            MessageBox.Show("Tool_Save_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 預排單保存
    ''' </summary>
    ''' <param name="fDeliverId">送貨單號</param>
    ''' <param name="fOldDeliverId">老送貨單號</param>
    ''' <param name="fSaleOrdeNo">銷售單號</param>
    ''' <param name="AreaCode">區域編號</param>
    ''' <param name="fDeliverDate">送貨日期</param>
    ''' <param name="fAddressName">送貨地址</param>
    ''' <param name="fConsigneeMan">聯系人</param>
    ''' <param name="fTelphone">電話</param>
    ''' <param name="fRemark">備注</param>
    ''' <param name="fTructCode">車名</param>
    ''' <param name="DGView">貨品網格</param>
    ''' <param name="EditBool">是否是修改</param>
    ''' <param name="Index">TabPagIndex當前頁面</param>
    ''' <param name="IsUnioBool">是否是合並</param>
    ''' <param name="fAreaId">區域ID(是否改變線路)</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Tool_YPSaveData(ByVal fDeliverId As String, ByVal fOldDeliverId As String, ByVal fSaleOrdeNo As String, ByVal AreaCode As String, ByVal fDeliverDate As String, ByVal fAddressName As String, ByVal fConsigneeMan As String, ByVal fTelphone As String, ByVal fRemark As String, ByVal fTructCode As String, ByVal DGView As DataGridView, ByVal EditBool As Boolean, ByVal Index As Integer, _
                                     ByRef IsUnioBool As Boolean, ByVal fAreaId As String, ByVal fCarName As String, ByVal fTruckName As String) As Boolean
        Dim Bool As Boolean = True

        Dim SqlCn As SqlConnection = GetConn()
        Dim SqlCmd As New SqlCommand
        Dim SqlTran As SqlTransaction = SqlCn.BeginTransaction
        Dim SqlBluck As SqlBulkCopy
        Dim Sql As String = ""
        Try

            Dim DtabGoods As DataTable = DirectCast(DGView.DataSource, DataTable)
            Dim DetailDtab As DataTable = Me.Re_SaveDataTable(DtabGoods, 1, fDeliverId, fSaleOrdeNo)

            Dim SaleOrdeB As DataTable = Me.Re_Sal_SaleOrdeBDataTable(fSaleOrdeNo)
            Dim SplitBool As Boolean = Return_IsSplitGoods(DetailDtab, SaleOrdeB)

            Dim DetailDtabA As New DataTable
            Dim fAreaCode As String = ""
            If Val(fAreaId) <= 0 Then
                fAreaCode = "Null"
            Else
                fAreaCode = fAreaId
            End If

            If SplitBool = True AndAlso fDeliverId.Trim <> fOldDeliverId.Trim Then
                If Return_IsExistsDeliverInfo(fDeliverId, fSaleOrdeNo) = True Then

                    ''處理數據合並
                    Dim TextValue As New System.Text.StringBuilder
                    Dim Union As String = " Union " & vbCrLf
                    Dim TSql As String = ""
                    For Each Row As DataRow In DetailDtab.Rows
                        Dim ItemNo As String = Row("ItemNo") & ""
                        Dim fGoodsBarCode As String = Row("fGoodsBarCode")
                        Dim fTotal As String = Val(Row("fTotal") & "")
                        Dim fStatus As Integer = 0

                        Dim QStr As String = "  select '" & fDeliverId & "'  as fDeliverId,'" & fSaleOrdeNo & "'  as fSaleOrdeNo,'" & ItemNo & "'  as ItemNo,'" & fGoodsBarCode & "' as fGoodsBarCode," & fTotal & " as fTotal," & fStatus & "  as fStatus" & vbCrLf
                        If TextValue.ToString.Trim <> "" Then
                            TextValue.Append(Union)
                        End If
                        TextValue.Append(QStr)
                    Next

                    If TextValue.ToString.Trim <> "" Then
                        Dim TabC As String = System.Guid.NewGuid().ToString & ""

                        TSql &= " select fDeliverId,fSaleOrdeNo,ItemNo,fGoodsBarCode,Isnull(Sum(fTotal),0) as fTotal,fStatus  Into[#" & TabC & "] from ( "
                        TSql &= " select fDeliverId,fSaleOrdeNo,ItemNo,fGoodsBarCode,fTotal,0 as fStatus  from DeliverGoodsInfo where fDeliverId='" & fDeliverId & "' and fSaleOrdeNo='" & fSaleOrdeNo & "' " & vbCrLf
                        TSql &= " Union" & vbCrLf
                        TSql &= " " & TextValue.ToString.Trim & vbCrLf
                        TSql &= " ) a group by fDeliverId,fSaleOrdeNo,ItemNo,fGoodsBarCode,fStatus " & vbCrLf & vbCrLf

                        TSql &= " select * from (" & vbCrLf
                        TSql &= " select Isnull(a.fTotal,0)-Isnull(b.fSumCount,0)  as fTotal from [#" & TabC & "] a " & vbCrLf
                        TSql &= " inner join dbo.Sal_SaleOrdeB b  on a.fSaleOrdeNo=b.fSaleOrdeNo and a.ItemNo=b.ItemNo  where a.fDeliverId='" & fDeliverId & "' and a.fSaleOrdeNo='" & fSaleOrdeNo & "') a where Isnull(fTotal,0)<0" & vbCrLf & vbCrLf

                        TSql &= " select a.fDeliverId,a.fSaleOrdeNo,a.ItemNo,a.fGoodsBarCode,a.fTotal,convert(decimal(18,2),(b.fSumMoney/b.fSumCount)*a.fTotal) as fSumMoney,a.fStatus  from [#" & TabC & "] a inner join Sal_SaleOrdeB b on (a.fSaleOrdeNo=b.fSaleOrdeNo and a.ItemNo=b.ItemNo)  order by a.ItemNo " & vbCrLf & vbCrLf
                        TSql &= " Drop table [#" & TabC & "]" & vbCrLf

                        Dim Dset As New DataSet
                        Dset = Exec(TSql, E_ExecType.DataSet)
                        If Dset.Tables(0).Rows.Count <= 0 Then
                            IsUnioBool = True
                            DetailDtabA = Dset.Tables(1).Copy
                        End If
                    End If

                End If
            End If


            If EditBool = False Then

                Sql &= "  Insert Into DeliverGoodsMaster(fDeliverId,fCarNo,fDeliverDate,Status,BuildDate,BuildPsn,BuildComputer,fTructCode,fCarName,fTruckName)" & vbCrLf
                Sql &= "  values('" & fDeliverId & "','" & AreaCode & "','" & fDeliverDate & "','A',Getdate(),'" & PubUserName & "','" & My.Computer.Name & "','" & fTructCode & "','" & fCarName & "','" & fTruckName & "')" & vbCrLf

                Sql &= "  Delete DeliverGoodsDetail where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fDeliverId & "'" & vbCrLf
                Sql &= "  Delete DeliverGoodsDetail where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fOldDeliverId & "'" & vbCrLf
                Sql &= "  Insert Into DeliverGoodsDetail(fDeliverId,fSaleOrdeNo,fAddressName,fConsigneeMan,fTelphone,fRemark,fStatus,fSplitStatus,fAreaCode) " & vbCrLf
                Sql &= "  values('" & fDeliverId & "','" & fSaleOrdeNo & "','" & fAddressName & "','" & fConsigneeMan & "','" & fTelphone & "','" & fRemark & "',0,'" & IIf(SplitBool = True, 1, 0) & "'," & fAreaCode & ")" & vbCrLf

            Else

                Sql &= "  Delete DeliverGoodsDetail where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fDeliverId & "'" & vbCrLf
                Sql &= "  Delete DeliverGoodsDetail where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fOldDeliverId & "'" & vbCrLf
                Sql &= "  Update DeliverGoodsMaster set UpdateDate=Getdate(),UpdatePsn='" & PubUserName & "',UpdateComputer='" & My.Computer.Name & "',fTructCode='" & fTructCode & "',fCarName='" & fCarName & "',fTruckName='" & fTruckName & "'    where fDeliverId='" & fDeliverId & "'" & vbCrLf
                Sql &= "  Insert Into DeliverGoodsDetail(fDeliverId,fSaleOrdeNo,fAddressName,fConsigneeMan,fTelphone,fRemark,fStatus,fSplitStatus,fAreaCode) " & vbCrLf
                Sql &= "  values('" & fDeliverId & "','" & fSaleOrdeNo & "','" & fAddressName & "','" & fConsigneeMan & "','" & fTelphone & "','" & fRemark & "',0,'" & IIf(SplitBool = True, 1, 0) & "'," & fAreaCode & ")" & vbCrLf

            End If

            Dim TableA As String = System.Guid.NewGuid().ToString
            Dim TableB As String = System.Guid.NewGuid().ToString

            Sql &= " Delete DeliverGoodsInfo where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fOldDeliverId & "'" & vbCrLf
            Sql &= " Delete DeliverGoodsInfo where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fDeliverId & "'" & vbCrLf
            Sql &= " Delete DeliverGoodsMaster where fDeliverId not in (select fDeliverId from DeliverGoodsDetail)" & vbCrLf
            ''更新定單
            'Sql &= " Update Sal_SaleOrdeA set  fDeliverAddress='" & fAddressName & "',fLinkMan='" & fConsigneeMan & "',fLinkPhone='" & fTelphone & "',fRemark='" & fRemark & "'  " & IIf(fAreaId.Trim <> "", "  ,fAreaId='" & fAreaId & "'  ", "  ") & "  from Sal_SaleOrdeA  where Isnull(fSaleOrdeNo,'')='" & fSaleOrdeNo & "'"
            'Sql &= " Update Sal_SaleOrdeA set   fLinkMan='" & fConsigneeMan & "',fLinkPhone='" & fTelphone & "',fRemark='" & fRemark & "'  " & IIf(fAreaId.Trim <> "", "  ,fAreaId='" & fAreaId & "'  ", "  ") & "  from Sal_SaleOrdeA  where Isnull(fSaleOrdeNo,'')='" & fSaleOrdeNo & "'"

            With SqlCmd
                .CommandText = Sql
                .CommandType = CommandType.Text
                .Connection = SqlCn
                .Transaction = SqlTran
                .ExecuteNonQuery()
            End With

            SqlBluck = New SqlBulkCopy(SqlCn, SqlBulkCopyOptions.Default, SqlTran)
            With SqlBluck
                .DestinationTableName = "DeliverGoodsInfo"
                .BulkCopyTimeout = 100

                If IsUnioBool = True Then
                    ''合並
                    .WriteToServer(DetailDtabA)
                Else
                    .WriteToServer(DetailDtab)
                End If

            End With

            SqlTran.Commit()
            Bool = True
        Catch ex As Exception
            MessageBox.Show("Tool_YPSaveData:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            SqlTran.Rollback()
            Bool = False
        End Try
        Return Bool
    End Function

    ''' <summary>
    ''' 取消
    ''' </summary>
    ''' <param name="TabIndex"></param>
    ''' <remarks></remarks>
    Private Sub Tool_Cancel_Click(ByVal TabIndex As Integer)
        Try
            Select Case TabIndex
                Case 1

                Case 2

                    Dim Node As TreeNode = Me.Tvw_2_1.SelectedNode
                    If Node.Checked = False Then Exit Sub

                    If MessageBox.Show("確認要取消預排單嗎？", Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then

                        Dim fSaleOrdeNo As String = Node.Tag.ToString.Split(":")(4).Trim

                        Dim Sql As String = "  delete dbo.DeliverGoodsDetail where Isnull(fSaleOrdeNo,'')='" & fSaleOrdeNo & "' " & vbCrLf
                        Exec(Sql, E_ExecType.ExecuteNonQuery)

                        Me.txtfDestineDate.Text = ""
                        Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("fSaleOrdeNo='" & fSaleOrdeNo & "'")
                        If DRow.Length > 0 Then
                            DRow(0).Item("fDestineDate") = ""
                            DRow(0).Item("fDateKey") = DRow(0).Item("fDeliverDate")
                        End If
                        Sal_SaleOrdeA.AcceptChanges()
                        MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If

                Case 3
                    setControlsbEnabled(New Control() {Me.TabControl3.TabPages(0)}, False)
                    Action = IDServer.IDServer.ActionBtn.ActionHelp
                    Me.btnPrevious.Enabled = True
                    Me.btnNext.Enabled = False
                    ''網格不可以用只能修改一行
                    Me.DGV_3_1.Enabled = True
                    DGView_3_2.ReadOnly = True
                    If Me.DGV_3_1.Rows.Count > 0 Then
                        Me.txtfSaleOrdeNo_Filter.ReadOnly = False
                    Else
                        Me.txtfSaleOrdeNo_Filter.ReadOnly = True
                    End If
                    Me.cbx_AreaCode.Enabled = True
                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("Tool_Cancel_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 刪除溝通記錄
    ''' </summary>
    ''' <param name="DGView">网格</param>
    ''' <remarks></remarks>
    Private Sub Tool_Delete_Click(ByRef DGView As DataGridView)
        Try

            If DGView.CurrentRow Is Nothing Then Exit Sub

            If MessageBox.Show(My.resources.ConfirmDelete, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then

                Dim ItemNo As Integer = Val(DGView.CurrentRow.Cells("ItemNo").Value & "")
                Dim fSaleOrdeNo As String = DGView.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                Dim Dtab As DataTable = DirectCast(DGView.DataSource, DataTable)
                Dim DRow() As DataRow = Dtab.Select("", "ItemNo Desc")
                If DRow.Length <= 0 Then
                    MessageBox.Show("沒有一條記錄。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                If ItemNo <> Val(DRow(0).Item("ItemNo") & "") Then
                    MessageBox.Show("只能刪除最後一條溝通記錄。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If


                Dim Sql As String = " Delete Des_CustomerRecord where Isnull(fSaleOrdeNo,'')='" & fSaleOrdeNo & "' and ItemNo=" & ItemNo & ""

                Exec(Sql, E_ExecType.ExecuteNonQuery)
                DRow(0).Delete()
                Dtab.AcceptChanges()
                DGView.Update()

                If DGView.Name.ToLower = Me.DGV_2_3.Name.ToLower Then
                    Me.txtfDestineRemark.Text = ""
                    DRow = Dtab.Select("", "ItemNo Desc")
                    If DRow.Length > 0 Then
                        Me.txtfDestineRemark.Text = DRow(0).Item("fRemark") & ""
                    End If
                End If
                MessageBox.Show(My.resources.DeleteSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

        Catch ex As Exception
            MessageBox.Show("Tool_Delete_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 刪除排單
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Tool_Delete_3_1_Click()
        Try
            If MessageBox.Show(My.resources.ConfirmDelete, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
                If Me.DGV_3_1.CurrentRow Is Nothing Then Exit Sub

                Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
                Dim fDeliverId As String = Me.DGV_3_1.CurrentRow.Cells("fDeliverId").Value & ""
                Dim fSaleOrdeNo As String = Me.DGV_3_1.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                Dim Index As Integer = Me.DGV_3_1.CurrentRow.Index - 1

                Dim Sql As String = " "

                Sql &= " Delete DeliverGoodsDetail where fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fDeliverId & "'" & vbCrLf
                Sql &= " Delete dbo.DeliverGoodsInfo where fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fDeliverId & "'" & vbCrLf
                Sql &= " if not exists(select * from DeliverGoodsDetail where fDeliverId='" & fDeliverId & "')" & vbCrLf
                Sql &= "     Begin" & vbCrLf
                Sql &= "         Delete dbo.DeliverGoodsMaster where fDeliverId='" & fDeliverId & "' " & vbCrLf
                Sql &= "     End" & vbCrLf

                Exec(Sql, E_ExecType.ExecuteNonQuery)
                Dim DRow() As DataRow = Dtab.Select("fDeliverId='" & fDeliverId & "'  and  fSaleOrdeNo='" & fSaleOrdeNo & "'")
                If DRow.Length > 0 Then
                    DRow(0).Delete()
                End If
                Dtab.AcceptChanges()
                Me.DGV_3_1.Update()

                If Index >= 0 AndAlso Me.DGV_3_1.RowCount > Index Then
                    Me.DGV_3_1.CurrentCell = Me.DGV_3_1.Rows(Index).Cells("fSaleOrdeNo")
                    Me.DGV_3_1.ClearSelection()
                    Me.DGV_3_1.CurrentRow.Selected = True
                Else
                    If Me.DGV_3_1.RowCount > 0 Then
                        Me.DGV_3_1.CurrentCell = Me.DGV_3_1.Rows(0).Cells("fSaleOrdeNo")
                        Me.DGV_3_1.ClearSelection()
                        Me.DGV_3_1.CurrentRow.Selected = True
                    End If
                End If

                MessageBox.Show(My.resources.DeleteSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If
        Catch ex As Exception
            MessageBox.Show("Tool_Delete_3_1_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 折分貨品
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Tool_SplitGoods_Click()
        Try

            If TabControl3.SelectedIndex <> 1 Then
                TabControl3.SelectedIndex = 1
            End If

            Dim frm As New Frm_SplitGoods

            Dim fSaleOrdeNo As String = ""
            Dim fDeliverId As String = ""

            If Not Me.DGV_3_1.CurrentRow Is Nothing Then
                fSaleOrdeNo = Me.DGV_3_1.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                fDeliverId = Me.DGV_3_1.CurrentRow.Cells("fDeliverId").Value & ""
            End If
            frm.Set_fSaleOrdeNo = fSaleOrdeNo
            frm.Set_fDeliverId = fDeliverId
            If frm.ShowDialog() = DialogResult.OK Then

                Dim DGView As DataGridView = frm.DGView_1
                Dim Dtab As DataTable = DirectCast(DGView.DataSource, DataTable)

                Dim DtabA As DataTable = DirectCast(Me.DGView_3_2.DataSource, DataTable)
                DtabA.Clear()
                DtabA.AcceptChanges()

                Dim DRow() As DataRow = Dtab.Select("CheckA=True")
                For Each Row As DataRow In DRow
                    Dim MRow As DataRow = DtabA.NewRow
                    For Each Col As DataColumn In Dtab.Columns
                        If DtabA.Columns.Contains(Col.ColumnName) = True Then
                            MRow(Col.ColumnName) = Row(Col.ColumnName)
                        End If
                    Next
                    DtabA.Rows.Add(MRow)
                Next
                DtabA.AcceptChanges()
                Me.DGV_3_1.Update()
            End If

        Catch ex As Exception
            MessageBox.Show("Tool_SplitGoods_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 跨區安排
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Tool_ChangArea_Click(ByVal TabIndex As Integer)
        Try
            Dim frm As New Frm_SelectAreaCode
            Dim OldfDeliverId As String = ""
            Dim fSaleOrdeNo As String = ""
            Dim DGVGoods As New DataGridView
            Dim fTruckId As String = ""
            Dim fTruckName As String = ""

            Select Case TabIndex
                Case 2
                    Dim Node As TreeNode = Me.Tvw_2_1.SelectedNode
                    Select Case Node.Level

                        Case 3 ''整個地方跨區

                            ''驗證是否可以跨區
                            Dim KeyText As String = Node.Tag.ToString.Trim
                            Dim fAreaId As String = KeyText.Split(":")(3).Trim
                            Dim fSaleDate As String = KeyText.Split(":")(2).Trim
                            Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId02,'')='" & fAreaId & "'  and fSaleDate='" & fSaleDate & "'")

                            Dim PPDrow() As DataRow = Me.Sal_SaleOrdeA.Select("Isnull(fAreaId02,'')='" & fAreaId & "' and fDeliverId<>''")
                            If PPDrow.Length > 0 Then

                                MessageBox.Show(Node.Text.Trim & "地區已有安排的送貨單,不能一起跨區安排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                                GoTo A
                            End If
                            Dim fDateHash As New Hashtable
                            Dim TextStr As New System.Text.StringBuilder
                            Dim fDateKey As String = ""

                            If DRow.Length > 0 Then
                                For Each Row As DataRow In DRow
                                    If fDateHash.ContainsKey(Row("fDateKey") & "") = False AndAlso IsDate(Row("fDateKey") & "") = True Then
                                        fDateHash.Add(Row("fDateKey") & "", Row("fDateKey") & "")
                                        fDateKey = Row("fDateKey") & ""
                                    End If
                                    If TextStr.ToString.Trim <> "" Then
                                        TextStr.Append(",")
                                    End If
                                    TextStr.Append(Row("fSaleOrdeNo") & "")
                                Next

                                If fDateHash.Count <> 1 Then
                                    MessageBox.Show(Node.Text.Trim & "地區有多個送貨時間,不能一起跨區安排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                                    GoTo A
                                End If

                            Else
                                GoTo A
                            End If

                            frm.fIndex = 1
                            frm.Set_OldLineCode = KeyText.Split(":")(1).Trim
                            If IsDate(fDateKey) = True Then
                                frm.Set_fDeliverDate = fDateKey
                                frm.DateTimePicker1.Text = fDateKey
                            End If
                            If frm.ShowDialog = DialogResult.OK Then

                                Dim fDeliverId As String = ""
                                Dim AreaCode As String = ""
                                Dim Sql As String = ""

                                Dim TNode As TreeNode = frm.TreeView1.SelectedNode
                                Dim B() As String = TNode.Tag.ToString.Trim.Split(":")

                                If Not frm.cbx_TruckName.SelectedValue Is Nothing Then
                                    fTruckId = frm.cbx_TruckName.SelectedValue & ""
                                End If
                                fTruckName = frm.cbx_TruckName.Text.Trim & ""

                                Dim fCarName As String = TNode.Text

                                Dim ParentId As String = B(1).Trim
                                Dim Id As String = B(2).Trim

                                Dim fDeliverDate As String = frm.DateTimePicker1.Text
                                Dim SRow() As DataRow = BSC_AreaSetDtab.Select("Id=" & Val(ParentId) & "")
                                If SRow.Length > 0 Then
                                    AreaCode = SRow(0).Item("AreaCode")
                                End If
                                fDeliverId = Format(CType(fDeliverDate, DateTime), "yyMMdd") & AreaCode & "-" & fTruckId

                                Dim Status As String = ""

                                Dim EditBool As Boolean = IsExistsfDeliverId(AreaCode, fDeliverDate, Status, fTruckId)

                                If Status.ToLower = "B".ToLower OrElse Status.ToLower = "F".ToLower Then
                                    MessageBox.Show("排程單" & fDeliverId & "已" & Status.Replace("B", "核准").Replace("F", "結案") & "不能再排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                                    Exit Sub
                                End If


                                If EditBool = True Then

                                Else
                                    Sql &= "  Insert Into DeliverGoodsMaster(fDeliverId,fCarNo,fDeliverDate,Status,BuildDate,BuildPsn,BuildComputer,fTructCode,fCarName,fTruckName)" & vbCrLf
                                    Sql &= "  values('" & fDeliverId & "','" & AreaCode & "','" & fDeliverDate & "','A',Getdate(),'" & PubUserName & "','" & My.Computer.Name & "','" & fTruckId & "','" & fCarName & "','" & fTruckName & "')" & vbCrLf & vbCrLf
                                End If

                                Sql &= " Insert Into DeliverGoodsDetail(" & vbCrLf
                                Sql &= " fDeliverId, fSaleOrdeNo, SiteNo, fAddressName, fConsigneeMan, fTelphone, fAecceptDate, fRemark" & vbCrLf
                                Sql &= " )" & vbCrLf
                                Sql &= " select fDeliverId='" & fDeliverId & "',fSaleOrdeNo,0 as SiteNo,fDeliverAddress,fLinkMan,fLinkPhone,Null,fRemark" & vbCrLf
                                Sql &= " from Sal_SaleOrdeA where fSaleOrdeNo in('" & TextStr.ToString.Trim.Replace(",", "','") & "')" & vbCrLf & vbCrLf

                                Sql &= " Insert Into DeliverGoodsInfo(fDeliverId,fSaleOrdeNo,ItemNo,fGoodsBarCode,fTotal,fSumMoney,fRemark)" & vbCrLf

                                Sql &= " select fDeliverId='" & fDeliverId & "',fSaleOrdeNo,ItemNo,fGoodsBarCode,fSumCount,fSumMoney,fRemark" & vbCrLf
                                Sql &= " from Sal_SaleOrdeB where fSaleOrdeNo in('" & TextStr.ToString.Trim.Replace(",", "','") & "')" & vbCrLf & vbCrLf

                                ''更新訂單(不須要更新---不能改變原始單)
                                ''Sql &= " Update Sal_SaleOrdeA set  fAreaId='" & Id & "'  from Sal_SaleOrdeA  where fSaleOrdeNo in('" & TextStr.ToString.Trim.Replace(",", "','") & "')" & vbCrLf
                                ''改變區域時存儲區域
                                Sql &= " update DeliverGoodsDetail set fAreaCode='" & Id & "' where fDeliverId='" & fDeliverId & "'  and fSaleOrdeNo in ('" & TextStr.ToString.Trim.Replace(",", "','") & "')" & vbCrLf


                                Exec(Sql, E_ExecType.ExecuteNonQuery)


                                For Each Row As DataRow In DRow

                                    Row("fDestineDate") = frm.DateTimePicker1.Text.Trim
                                    Row("fDateKey") = frm.DateTimePicker1.Text.Trim
                                    Row("fDeliverId") = fDeliverId
                                    Row("TruckName") = frm.cbx_TruckName.Text.Trim
                                    Row("fAreaId02") = Id
                                    Row("fAreaId01") = ParentId

                                Next
                                Sal_SaleOrdeA.AcceptChanges()
                                'For Each tempNode As TreeNode In Node.Nodes
                                '    tempNode.Remove()
                                'Next
                                Node.Nodes.Clear()
                                MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

                            End If

                            ''單獨處理 
A:
                            Exit Sub


                        Case 4 ''某一張單跨區
                            Dim A() As String = Node.Tag.ToString.Trim.Split(":")


                            frm.txtAddressName.Text = Me.txtDliverAddress.Text.Trim
                            frm.txtfConsigneeMan.Text = Me.txtReciveMan.Text.Trim
                            frm.txtfTelphone.Text = Me.txtCustomePhone.Text.Trim
                            frm.DateTimePicker1.Text = IIf(IsDate(Me.txtfDestineDate.Text) = True, Me.txtfDestineDate.Text, Me.txtfDeliverDate.Text)
                            frm.txtfRemark.Text = Me.txtfRemark.Text.Trim
                            frm.Set_OldLineCode = A(1).Trim
                            OldfDeliverId = A(5).Trim.Replace("＠", "")
                            fSaleOrdeNo = Me.txtfSaleOrdeNo.Text.Trim
                            DGVGoods = Me.DGV_2_1

                        Case Else

                    End Select


                Case 3

                    frm.txtAddressName.Text = Me.txtfAddressName_3_1.Text.Trim
                    frm.txtfConsigneeMan.Text = Me.txtfConsigneeMan_3_1.Text.Trim
                    frm.txtfTelphone.Text = Me.txtfTelphone_3_1.Text.Trim
                    frm.txtfRemark.Text = Me.txtfRemark_3_1.Text.Trim
                    frm.DateTimePicker1.Text = txtfDeliverDate_3_1.Text
                    Dim Node As TreeNode = Me.Tvw_3_1.SelectedNode
                    Dim A() As String = Node.Tag.ToString.Split(":")
                    frm.Set_OldLineCode = A(1).Trim
                    If Not Me.DGV_3_1.CurrentRow Is Nothing Then
                        OldfDeliverId = Me.DGV_3_1.CurrentRow.Cells("fDeliverId").Value & ""
                        fSaleOrdeNo = Me.DGV_3_1.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                    End If
                    DGVGoods = Me.DGView_3_2

                Case Else

            End Select
            If frm.ShowDialog = DialogResult.OK Then

                Dim TNode As TreeNode = frm.TreeView1.SelectedNode
                Dim B() As String = TNode.Tag.ToString.Trim.Split(":")

                If Not frm.cbx_TruckName.SelectedValue Is Nothing Then
                    fTruckId = frm.cbx_TruckName.SelectedValue & ""
                End If
                fTruckName = frm.cbx_TruckName.Text.Trim & ""

                Dim ParentId As String = B(1).Trim
                Dim Id As String = B(2).Trim
                Dim fDeliverId As String = ""
                Dim AreaCode As String = ""
                Dim fCarName As String = ""

                Dim fDeliverDate As String = frm.DateTimePicker1.Text.Trim

                Dim fAddressName As String = frm.txtAddressName.Text.Trim
                Dim fConsigneeMan As String = frm.txtfConsigneeMan.Text.Trim
                Dim fTelphone As String = frm.txtfTelphone.Text.Trim
                Dim fRemark As String = frm.txtfRemark.Text.Trim


                Dim DRow() As DataRow = BSC_AreaSetDtab.Select("Id=" & Val(ParentId) & "")
                If DRow.Length > 0 Then
                    AreaCode = DRow(0).Item("AreaCode") & ""
                    fCarName = DRow(0).Item("AreaName") & ""
                End If

                fDeliverId = Format(CType(fDeliverDate, DateTime), "yyMMdd") & AreaCode & "-" & fTruckId

                Dim Status As String = ""

                Dim EditBool As Boolean = IsExistsfDeliverId(AreaCode, fDeliverDate, Status, fTruckId)

                If Status.ToLower = "B".ToLower OrElse Status.ToLower = "F".ToLower Then
                    MessageBox.Show("排程單" & fDeliverId & "已" & Status.Replace("B", "核准").Replace("F", "結案") & "不能再排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                Dim Bool As Boolean = False
                ''未安排跨線
                If OldfDeliverId.Trim = "" Then

                    Dim IsUnionBool As Boolean = False
                    Bool = Tool_YPSaveData(fDeliverId, OldfDeliverId, fSaleOrdeNo, AreaCode, fDeliverDate, fAddressName, fConsigneeMan, fTelphone, fRemark, fTruckId, DGVGoods, EditBool, 2, IsUnionBool, Id, fCarName, fTruckName)

                Else
                    ''已安排跨線
                    Dim Sql As String = ""
                    If EditBool = True Then
                        Sql &= "  Update DeliverGoodsMaster set fTructCode='" & fTruckId & "'   where fDeliverId='" & fDeliverId & "'" & vbCrLf
                    Else
                        Sql &= "  Insert Into DeliverGoodsMaster(fDeliverId,fCarNo,fDeliverDate,Status,BuildDate,BuildPsn,BuildComputer,fTructCode,fCarName,fTruckName)" & vbCrLf
                        Sql &= "  values('" & fDeliverId & "','" & AreaCode & "','" & fDeliverDate & "','A',Getdate(),'" & PubUserName & "','" & My.Computer.Name & "','" & fTruckId & "','" & fCarName & "','" & fTruckName & "')" & vbCrLf & vbCrLf
                    End If
                    Sql &= " Update DeliverGoodsDetail set fDeliverId='" & fDeliverId & "',fAddressName='" & fAddressName & "',fConsigneeMan='" & fConsigneeMan & "',fTelphone='" & fTelphone & "',fRemark='" & fRemark & "' where fDeliverId='" & OldfDeliverId & "' and fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf
                    Sql &= " Update DeliverGoodsInfo set fDeliverId='" & fDeliverId & "' where fDeliverId='" & OldfDeliverId & "' and fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf & vbCrLf
                    Sql &= " Delete DeliverGoodsMaster where fDeliverId not in (select distinct fDeliverId from DeliverGoodsDetail) " & vbCrLf

                    'Sql &= " Update Sal_SaleOrdeA set  fDeliverAddress='" & fAddressName & "',fLinkMan='" & fConsigneeMan & "',fLinkPhone='" & fTelphone & "',fRemark='" & fRemark & "',fAreaId='" & Id & "'  from Sal_SaleOrdeA  where Isnull(fSaleOrdeNo,'')='" & fSaleOrdeNo & "'"

                    Sql &= " update DeliverGoodsDetail set fAreaCode='" & Id & "' where fDeliverId='" & fDeliverId & "'  and fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf

                    Exec(Sql, E_ExecType.ExecuteNonQuery, True)

                End If

                ''更新數據
                Select Case TabIndex

                    Case 2
                        UpdateData(fAddressName, fConsigneeMan, fTelphone, fDeliverDate, fRemark, fSaleOrdeNo, fDeliverId, OldfDeliverId, fTruckName, False, Id, ParentId)
                        Dim Node As TreeNode = Me.Tvw_2_1.SelectedNode
                        Dim NewTag As String = ""
                        Dim A() As String = Node.Tag.ToString.Trim.Trim.Split(":")
                        A(1) = ParentId.Trim
                        A(2) = fDeliverDate.Trim
                        A(3) = Id.Trim
                        A(5) = "＠" & fDeliverId.Trim

                        For Each Textstr As String In A
                            If NewTag.Trim <> "" Then
                                NewTag += ":"
                            End If
                            NewTag += Textstr
                        Next

                        Delete_TreeNode(Me.Tvw_2_1, Node, NewTag)
                    Case 3
                        UpdateData(fAddressName, fConsigneeMan, fTelphone, fDeliverDate, fRemark, fSaleOrdeNo, fDeliverId, OldfDeliverId, fTruckName, False, Id, ParentId)
                        Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
                        Dim PRow() As DataRow = Dtab.Select("fSaleOrdeNo='" & fSaleOrdeNo & "' and Isnull(fDeliverId,'')='" & OldfDeliverId & "'")
                        For Each Row As DataRow In PRow
                            Row.Delete()
                        Next
                        Dtab.AcceptChanges()
                        Me.DGV_3_1.Update()
                        Me.DGV_3_1.Refresh()

                End Select
                MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If
        Catch ex As Exception
            MessageBox.Show("Tool_ChangArea_Click:" & ex.Message & ex.Source, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 刪除樹結點
    ''' </summary>
    ''' <param name="Tvw">樹</param>
    ''' <param name="OldNode">老結點</param>
    ''' <param name="NewTag">新結點的Tag</param>
    ''' <remarks></remarks>
    Private Sub Delete_TreeNode(ByRef Tvw As TreeView, ByRef OldNode As TreeNode, ByVal NewTag As String)
        Try
            If OldNode Is Nothing Then Exit Sub

            Dim ParentNode As TreeNode = OldNode.Parent
            Dim NextNode As TreeNode = OldNode.NextNode
            Dim PrevNode As TreeNode = OldNode.PrevNode

            ParentNode.Nodes.Remove(OldNode)
            If Not NextNode Is Nothing Then
                Tvw.SelectedNode = NextNode
            ElseIf Not PrevNode Is Nothing Then
                Tvw.SelectedNode = PrevNode
            Else
                Tvw.SelectedNode = ParentNode
            End If

            ''添加新結點
            'Add_TreeNode(Tvw, NewTag)

        Catch ex As Exception
            MessageBox.Show("Delete_TreeNode:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Add_TreeNode(ByVal Tvw As TreeView, ByVal NewTag As String)
        Try
            Dim A() As String = NewTag.Trim.Split(":")
            Dim Tag As String = A(0) & ":" & A(1)

            Dim ParentNode As TreeNode = GetNodeByTag(Tvw, Tag)

            If ParentNode Is Nothing Then Exit Sub
            ''還未展開
            If ParentNode.Nodes.Count = 1 AndAlso ParentNode.Nodes(0).Text.Trim = "...".Trim Then Exit Sub
            Dim Bool As Boolean = False
            Tag = A(0) & ":" & A(1) & ":" & A(2)

            For Each Tnode As TreeNode In ParentNode.Nodes
                If Tnode.Tag.ToString.Trim.ToLower = Tag.ToLower Then '' 送貨日期
                    If Tnode.Nodes.Count = 1 AndAlso Tnode.Nodes(0).Text.Trim = "...".Trim Then Exit Sub
                    Dim NTag As String = A(0) & ":" & A(1) & ":" & A(2) & ":" & A(3)
                    For Each SNode As TreeNode In Tnode.Nodes    ''區域
                        If SNode.Tag.ToString.Trim.ToLower = NTag.Trim.ToLower Then
                            If Tnode.Nodes.Count = 1 AndAlso Tnode.Nodes(0).Text.Trim = "...".Trim Then Exit Sub
                        Else
                            Dim Pnode As TreeNode = SNode.Nodes.Add(A(4))
                            Pnode.Tag = NewTag
                        End If
                    Next
                    Exit Sub
                End If
            Next
        Catch ex As Exception
            MessageBox.Show("Add_TreeNode:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

#End Region

#Region "數據處理"

    ''' <summary>
    ''' 是否存在本次送貨
    ''' </summary>
    ''' <param name="fCarNo">車次</param>
    ''' <param name="fDeliverDate">送貨日期</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function IsExistsfDeliverId(ByVal fCarNo As String, ByVal fDeliverDate As String, ByRef Status As String, ByVal fTructCode As String) As Boolean
        Dim Bool As Boolean = False
        Status = "A"
        Dim sql As String = "  select * from DeliverGoodsMaster where fCarNo='" & fCarNo & "' and Convert(varchar(10),fDeliverDate,21)='" & fDeliverDate & "'  and Isnull(fTructCode,'')='" & fTructCode & "'" & vbCrLf
        Dim Dtab As New DataTable
        Dtab = App.ReturnDataTable(sql)
        If Dtab.Rows.Count > 0 Then
            Bool = True
            Status = Dtab.Rows(0).Item("Status") & ""
        End If
        Return Bool
    End Function

    ''' <summary>
    ''' 更新數據
    ''' </summary>
    ''' <param name="fAddressName">送貨地址</param>
    ''' <param name="fConsigneeMan">聯系人</param>
    ''' <param name="fTelphone">電話</param>
    ''' <param name="fDestineDate">送貨日期</param>
    ''' <param name="fRemark">備注</param>
    ''' <param name="fDeliverId">送貨單號</param>
    ''' <param name="fOldDeliverId">老送貨單號</param>
    ''' <param name="fSaleOrdeNo">銷售單號</param>
    ''' <param name="fTructName">車名</param>
    ''' <param name="fAreaId01"></param>
    ''' <param name="bBool">是否要更新</param>
    ''' <param name="fAreaId02">調路線後的區域編號</param>
    ''' <remarks></remarks>
    Private Sub UpdateData(ByVal fAddressName As String, ByVal fConsigneeMan As String, ByVal fTelphone As String, ByVal fDestineDate As String, ByVal fRemark As String, ByVal fSaleOrdeNo As String, ByVal fDeliverId As String, ByVal fOldDeliverId As String, ByVal fTructName As String, Optional ByVal bBool As Boolean = True, Optional ByVal fAreaId02 As String = "", Optional ByVal fAreaId01 As String = "")


        If bBool = True Then
            Me.txtDliverAddress.Text = fAddressName
            Me.txtReciveMan.Text = fConsigneeMan
            Me.txtCustomePhone.Text = fTelphone
            Me.txtfDestineDate.Text = fDestineDate
            Me.txtfRemark.Text = fRemark
            Me.txtTruckName.Text = fTructName
        End If

        Dim DRow() As DataRow = Me.Sal_SaleOrdeA.Select("fSaleOrdeNo='" & fSaleOrdeNo & "' and Isnull(fDeliverId,'')='" & fOldDeliverId & "'")
        If DRow.Length > 0 Then
            DRow(0).Item("fRemark") = fRemark
            DRow(0).Item("fDeliverAddress") = fAddressName
            DRow(0).Item("LinkMan") = fConsigneeMan
            DRow(0).Item("Telphone") = fTelphone
            DRow(0).Item("fDestineDate") = fDestineDate
            DRow(0).Item("fDateKey") = fDestineDate
            DRow(0).Item("fDeliverId") = fDeliverId
            DRow(0).Item("TruckName") = fTructName
            If fAreaId02.Trim <> "" Then
                DRow(0).Item("fAreaId02") = fAreaId02
                DRow(0).Item("fAreaId01") = fAreaId01
            End If
        End If
        Sal_SaleOrdeA.AcceptChanges()
    End Sub

    ''' <summary>
    ''' 保存送貨單數據
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SaveData_3_1() As Boolean
        Try
            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)

            Dim Node As TreeNode = Me.Tvw_3_1.SelectedNode

            Dim fDeliverId As String = Me.lbfDeliverId.Text.Trim
            Dim fSaleOrdeNo As String = Me.txtfSaleOrdeNo_3_1.Text.Trim
            Dim fAddressName As String = Me.txtfAddressName_3_1.Text.Trim
            Dim fConsigneeMan As String = Me.txtfConsigneeMan_3_1.Text.Trim & ""
            Dim fTelphone As String = Me.txtfTelphone_3_1.Text.Trim
            Dim fRemark As String = Me.txtfRemark_3_1.Text.Trim & ""
            Dim SiteNo As Integer = Val(Me.nudSiteNo_3_1.Value & "")
            Dim Ticket As Integer = 0
            'Dim fAecceptDate As String = Me.mtbfAecceptDate1_3_1.Text.Trim & "/" & Me.mtbfAecceptDate2_3_1.Text.Trim
            Dim fAecceptDate As String = Me.txtfAecceptDate.Text.Trim
            Dim OutStoreHouse As String = ""

            If Me.cbxTicket.Text.Trim = "是" Then
                Ticket = 1
            End If

            Dim Sql As String = ""
            Dim SqlCn As SqlConnection = GetConn()
            Dim SqlCmd As New SqlCommand
            Dim SqlTran As SqlTransaction = SqlCn.BeginTransaction
            Dim SqlBluck As SqlBulkCopy

            Try

                Dim DtabGoods As DataTable = DirectCast(Me.DGView_3_2.DataSource, DataTable)
                Dim DetailDtab As DataTable = Me.Re_SaveDataTable(DtabGoods, 1, fDeliverId, fSaleOrdeNo)

                Dim SaleOrdeB As DataTable = Me.Re_Sal_SaleOrdeBDataTable(fSaleOrdeNo)
                Dim SplitBool As Boolean = Return_IsSplitGoods(DetailDtab, SaleOrdeB)

                Sql &= "  Delete DeliverGoodsDetail where Isnull(fDeliverId,'')='" & fDeliverId & "' and Isnull(fSaleOrdeNo,'')='" & fSaleOrdeNo & "'" & vbCrLf
                Sql &= "  Insert Into DeliverGoodsDetail(fDeliverId,fSaleOrdeNo,fAddressName,fConsigneeMan,fTelphone,fRemark,fStatus,SiteNo,Ticket,fAecceptDate,fSplitStatus,OutStoreHouse) " & vbCrLf
                Sql &= "  values('" & fDeliverId & "','" & fSaleOrdeNo & "','" & fAddressName & "','" & fConsigneeMan & "','" & fTelphone & "','" & fRemark & "',1," & SiteNo & "," & Ticket & ",'" & fAecceptDate & "','" & IIf(SplitBool = True, 1, 0) & "','" & OutStoreHouse & "')"

                Sql &= "  Delete DeliverGoodsInfo where  fSaleOrdeNo='" & fSaleOrdeNo & "' and fDeliverId='" & fDeliverId & "'" & vbCrLf


                With SqlCmd
                    .CommandText = Sql
                    .CommandType = CommandType.Text
                    .Connection = SqlCn
                    .Transaction = SqlTran
                    .ExecuteNonQuery()
                End With


                SqlBluck = New SqlBulkCopy(SqlCn, SqlBulkCopyOptions.Default, SqlTran)
                With SqlBluck
                    .DestinationTableName = "DeliverGoodsInfo"
                    .BulkCopyTimeout = 100
                    .WriteToServer(DetailDtab)
                End With

                SqlTran.Commit()
            Catch ex As Exception
                SqlTran.Rollback()
                MessageBox.Show("保存出錯！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return False
            End Try

            setControlsbEnabled(New Control() {Me.TabControl3.TabPages(0)}, False)
            Action = IDServer.IDServer.ActionBtn.ActionHelp
            UpdateData_3_1()
            Me.btnPrevious.Enabled = True
            Me.btnNext.Enabled = False
            MessageBox.Show("數據保存成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            ''網格不可以用只能修改一行
            Me.DGV_3_1.Enabled = True
            If Me.DGV_3_1.Rows.Count > 0 Then
                Me.txtfSaleOrdeNo_Filter.ReadOnly = False
            Else
                Me.txtfSaleOrdeNo_Filter.ReadOnly = True
            End If
            DGView_3_2.ReadOnly = True
            Me.cbx_AreaCode.Enabled = True
            Return True
        Catch ex As Exception
            MessageBox.Show("SaveData_3_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 更新網格數據
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function UpdateData_3_1() As Boolean
        Try
            Dim fDeliverId As String = Me.lbfDeliverId.Text.Trim
            Dim fSaleOrdeNo As String = Me.txtfSaleOrdeNo_3_1.Text.Trim
            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)

            Dim DRow() As DataRow = Dtab.Select("fDeliverId='" & fDeliverId & "' and fSaleOrdeNo='" & fSaleOrdeNo & "'")
            If DRow.Length > 0 Then

                DRow(0).Item("CheckA") = 1
                DRow(0).Item("fAecceptDate") = Me.txtfAecceptDate.Text.Trim
                'DRow(0).Item("fAecceptDate2") = Me.mtbfAecceptDate2_3_1.Text.Trim
                DRow(0).Item("fConsigneeMan") = Me.txtfConsigneeMan_3_1.Text.Trim
                DRow(0).Item("fAddressName") = Me.txtfAddressName_3_1.Text.Trim
                DRow(0).Item("fTelphone") = Me.txtfTelphone_3_1.Text.Trim
                DRow(0).Item("fRemark") = Me.txtfRemark_3_1.Text.Trim
                DRow(0).Item("SiteNo") = Me.nudSiteNo_3_1.Value

            End If
            Dtab.AcceptChanges()
            Me.DGV_3_1.Update()
            Return True
        Catch ex As Exception
            MessageBox.Show("UpdateData_3_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 驗證TabPage3保有存數據
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Validated_3_1() As Boolean
        Try
            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
            Me.IsValidated = True
            If Me.txtfConsigneeMan_3_1.Text.Trim = "" Then
                MessageBox.Show("收貨人不能為空！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                If TabControl3.SelectedIndex <> 0 Then
                    TabControl3.SelectedIndex = 0
                End If
                Me.txtfConsigneeMan_3_1.Focus()
                Me.txtfConsigneeMan_3_1.SelectAll()
                Return False
            End If
            If Me.txtfAddressName_3_1.Text.Trim = "" Then
                MessageBox.Show("送貨地址不能為空！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                If TabControl3.SelectedIndex <> 0 Then
                    TabControl3.SelectedIndex = 0
                End If
                Me.txtfAddressName_3_1.Focus()
                Me.txtfAddressName_3_1.SelectAll()
                Return False
            End If
            If Me.txtfAecceptDate.Text.Trim = "" Then
                MessageBox.Show("沒有錄入時間！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                If TabControl3.SelectedIndex <> 0 Then
                    TabControl3.SelectedIndex = 0
                End If
                Me.txtfAecceptDate.Focus()
                Me.txtfAecceptDate.SelectAll()
                Return False
            End If
            Dim SiteNo As Integer = Val(Me.nudSiteNo_3_1.Value)
            'Dim DRow() As DataRow = Dtab.Select("Isnull(SiteNo,0)=" & SiteNo & "")
            'If DRow.Length > 1 Then
            '    MessageBox.Show("站點重複！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'End If

            Return True
        Catch ex As Exception
            MessageBox.Show("Validated_3_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            IsValidated = False
        End Try
    End Function

    ''' <summary>
    ''' 返回保存數據表
    ''' </summary>
    ''' <param name="SurDtab"></param>
    ''' <param name="Index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_SaveDataTable(ByVal SurDtab As DataTable, ByVal Index As Integer, Optional ByVal fDeliverId As String = "", Optional ByVal fSaleOrdeNo As String = "")
        Dim Dtab As New DataTable
        Try
            With Dtab.Columns
                .Add("fDeliverId", GetType(System.String))
                .Add("fSaleOrdeNo", GetType(System.String))
                .Add("ItemNo", GetType(System.String))
                .Add("fGoodsBarCode", GetType(System.String))
                .Add("fTotal", GetType(System.Double))
                .Add("fSumMoney", GetType(System.Double))
                .Add("fStatus", GetType(System.String))
                .Add("fHouseId", GetType(System.String))
            End With

            Select Case Index

                Case 1

                    For Each Row As DataRow In SurDtab.Rows
                        Dim MRow As DataRow = Dtab.NewRow
                        MRow("fDeliverId") = fDeliverId
                        MRow("fSaleOrdeNo") = fSaleOrdeNo
                        MRow("ItemNo") = Row("ItemNo")
                        MRow("fGoodsBarCode") = "*" & Row("fGoodsBarCode") & "*"
                        MRow("fTotal") = Val(Row("fGoodsamount") & "")
                        MRow("fSumMoney") = Val(Row("fSumMoney") & "")
                        MRow("fStatus") = 0
                        If SurDtab.Columns.Contains("fHouseId") = True Then
                            MRow("fHouseId") = Row("fHouseId")
                        Else
                            MRow("fHouseId") = ""
                        End If
                        Dtab.Rows.Add(MRow)
                    Next

                Case 2

                Case Else

            End Select

            Dtab.AcceptChanges()

        Catch ex As Exception
            MessageBox.Show("Re_SaveDataTable:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Dtab
    End Function

    ''' <summary>
    ''' 還可以出那些貨品
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_IsEnabledOutGoodsInfo(ByVal fDeliverId As String, ByVal fOldDeliverId As String, ByVal fSaleOrdeNo As String) As String
        Dim Sql As String = ""
        Try
            Dim TableA As String = System.Guid.NewGuid().ToString
            Dim TableB As String = System.Guid.NewGuid().ToString

            Sql &= " select a.fDeliverId,a.fSaleOrdeNo,b.ItemNo,b.fTotal into [#" & TableB & "] from DeliverGoodsDetail a" & vbCrLf
            Sql &= " inner join DeliverGoodsInfo b on (a.fDeliverId=b.fDeliverId and a.fSaleOrdeNo=b.fSaleOrdeNo)"
            Sql &= " where a.fDeliverId<>'" & fOldDeliverId & "' and a.fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf

            Sql &= " select fSaleOrdeNo,ItemNo,fGoodsBarCode,fSumCount,fRemark into[#" & TableA & "]  from dbo.Sal_SaleOrdeB where fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf

            Sql &= " update [#" & TableA & "] set fSumCount=fSumCount-b.fTotal from [#" & TableA & "] a inner join [#" & TableB & "] b on a.fSaleOrdeNo=b.fSaleOrdeNo and a.ItemNo=b.ItemNo" & vbCrLf

            Sql &= " select * from [#" & TableA & "] where Isnull(fSumCount,0)>0" & vbCrLf

            Sql &= " drop table [#" & TableA & "]" & vbCrLf

            Sql &= " drop table [#" & TableB & "]" & vbCrLf

        Catch ex As Exception
            MessageBox.Show("Re_IsEnabledOutGoodsInfo:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Sql
    End Function

    ''' <summary>
    ''' 驗證
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Validate_2_1(ByVal fDeliverId As String, ByVal fOldDeliverId As String, ByVal fSaleOrdeNo As String) As Boolean
        Try
            Dim sql As String = Me.Re_IsEnabledOutGoodsInfo(fDeliverId, fOldDeliverId, fSaleOrdeNo)
            Dim Dtab As New DataTable
            Dtab = Exec(sql, E_ExecType.DataTable)
            If Dtab.Rows.Count <= 0 Then
                MessageBox.Show("銷售定單(" & fSaleOrdeNo & ")已安排送貨，不能再預排。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return False
            End If
            Return True
        Catch ex As Exception
            MessageBox.Show("Validate_2_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 返回表Sal_SaleOrdeB
    ''' </summary>
    ''' <param name="fSaleOrdeNo"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_Sal_SaleOrdeBDataTable(ByVal fSaleOrdeNo As String) As DataTable
        Dim Dtab As New DataTable
        Try
            Dim Sql As String = "select * from Sal_SaleOrdeB where fSaleOrdeNo='" & fSaleOrdeNo & "' order by ItemNo"
            Dtab = Exec(Sql, E_ExecType.DataTable)
        Catch ex As Exception
            MessageBox.Show("Re_Sal_SaleOrdeBDataTable:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Dtab
    End Function

    ''' <summary>
    ''' 是否查分了貨品
    ''' </summary>
    ''' <param name="SurDtab">源表(網格中的數據)</param>
    ''' <param name="DestDtab">目的表(Sal_SaleOrdeB)</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Return_IsSplitGoods(ByVal SurDtab As DataTable, ByVal DestDtab As DataTable) As Boolean
        Dim Bool As Boolean = False
        Try
            If SurDtab.Rows.Count = DestDtab.Rows.Count Then
                Dim DRow() As DataRow = SurDtab.Select("", "ItemNo")
                For I As Integer = 0 To DRow.Length - 1
                    If DRow(I).Item("ItemNo").ToString.Trim.ToLower <> DestDtab.Rows(I).Item("ItemNo").ToString.Trim.ToLower _
                       OrElse Val(DRow(I).Item("fTotal") & "") <> Val(DestDtab.Rows(I).Item("fSumCount") & "") Then
                        Bool = True
                        Exit For
                    End If
                Next
            Else
                Bool = True
            End If
        Catch ex As Exception
            MessageBox.Show("IsSplitGoods:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Bool
    End Function

    ''' <summary>
    ''' 返回是否已存在送貨單號
    ''' </summary>
    ''' <param name="fDeliverId">送貨單號</param>
    ''' <param name="fSaleOrdeNo">銷售單號</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Return_IsExistsDeliverInfo(ByVal fDeliverId As String, ByVal fSaleOrdeNo As String) As Boolean
        Dim Bool As Boolean = False
        Dim Sql As String = " select fDeliverId,fSaleOrdeNo,ItemNo,fTotal,fStatus from DeliverGoodsInfo where fDeliverId='" & fDeliverId & "' and fSaleOrdeNo='" & fSaleOrdeNo & "' "
        Dim Dtab As DataTable
        Dtab = Exec(Sql, E_ExecType.DataTable)
        If Dtab.Rows.Count > 0 Then
            Bool = True
        End If
        Return Bool
    End Function

    ''' <summary>
    ''' 返回單據狀態
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReturnBillStatus(ByVal fDeliverId As String, ByVal fSaleOrdeNo As String) As String
        Dim BillStatus As String = "A"
        Try
            Dim Sql As String = ""

            Sql &= " select Isnull(BillStatus,'A') as BillStatus from DeliverGoodsDetail where fDeliverId='" & fDeliverId & "' and fSaleOrdeNo='" & fSaleOrdeNo & "'" & vbCrLf
            Dim Dtab As New DataTable

            Dtab = Exec(Sql, E_ExecType.DataTable)
            If Dtab.Rows.Count > 0 Then
                BillStatus = Dtab.Rows(0).Item("BillStatus") & ""
            End If
            If BillStatus.Trim = "" Then
                BillStatus = "A"
            End If
        Catch ex As Exception
            MessageBox.Show("ReturnBillStatus:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return BillStatus
    End Function

#End Region

#Region "添加事件"

    ''' <summary>
    ''' KeyDown 事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Text_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        Try
            Select Case e.KeyCode
                Case Keys.Enter
                    If e.Shift = True Then
                        If TypeOf sender Is ComboBox AndAlso CType(sender, ComboBox).DroppedDown = True Then
                            CType(sender, ComboBox).DroppedDown = False
                        End If
                        'SendKeys.Send("+{Tab}")
                        'SendKeys.Send("{F4}")
                    Else
                        If TypeOf sender Is ComboBox AndAlso CType(sender, ComboBox).DroppedDown = True Then
                            CType(sender, ComboBox).DroppedDown = False
                        End If
                        'SendKeys.Send("{Tab}")
                        'SendKeys.Send("{F4}")
                    End If
                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("Text_KeyDown:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 添加事件
    ''' </summary>
    ''' <param name="Pans"></param>
    ''' <remarks></remarks>
    Private Sub AddHandlers(ByVal Pans() As Control)
        Try
            For Each Pan As Control In Pans
                For Each Ctrl As Control In Pan.Controls
                    If TypeOf Ctrl Is TextBox _
                       OrElse TypeOf Ctrl Is ComboBox _
                       OrElse TypeOf Ctrl Is NumericUpDown _
                       OrElse TypeOf Ctrl Is MaskedTextBox Then
                        AddHandler Ctrl.KeyDown, AddressOf Text_KeyDown
                    End If
                Next
            Next
        Catch ex As Exception
            MessageBox.Show("AddHandlers:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "TabControl Change"

    Private Sub TabControl3_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl3.SelectedIndexChanged
        Try
            Dim Index As Integer = Me.TabControl3.SelectedIndex
            Select Case Index
                Case 0

                Case 1
                    'Dim fSaleOrdeNo As String = ""
                    'Dim fDeliverId As String = ""
                    'If Not DGV_3_1.CurrentRow Is Nothing AndAlso DGV_3_1.SelectedRows.Count > 0 Then
                    '    fDeliverId = DGV_3_1.CurrentRow.Cells("fDeliverId").Value.ToString.Trim & ""
                    '    fSaleOrdeNo = DGV_3_1.CurrentRow.Cells("fSaleOrdeNo").Value.ToString.Trim & ""
                    'End If
                    'FillDataGridDetail(fDeliverId, fSaleOrdeNo, 3)
                Case 2

            End Select
        Catch ex As Exception
            MessageBox.Show("TabControl3_SelectedIndexChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#End Region

#Region "Controls Events"

#Region "Form Load"


    'Private Sub TabControl1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TabControl1.KeyDown
    '    Try
    '        If Action = IDServer.IDServer.ActionBtn.ActionEdit Then
    '            If e.Modifiers = Keys.Control Then
    '                Select Case e.KeyCode
    '                    Case Keys.S

    '                        Tool_Save_Click()

    '                    Case Keys.Z
    '                        Dim TabIndex As Integer = Me.Re_SelectTabIndex()
    '                        Tool_Cancel_Click(TabIndex)
    '                    Case Else

    '                End Select
    '            End If
    '        End If
    '    Catch ex As Exception
    '        MessageBox.Show(":" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
    '    End Try
    'End Sub

    Private Sub Frm_OFSArrangeDeliveryDetail_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Me.fLoadBool = False
            Initialze()
            DynamicAddTabpage("TabPage1")
            setControlsbEnabled(New Control() {GroupBox3, Me.TabControl3.TabPages(0)}, False)
            AddHandlers(New Control() {GroupBox3, Me.TabControl3.TabPages(0)})
            Me.IsEditMode = False
            Me.fLoadBool = True
        Catch ex As Exception
            MessageBox.Show("Frm_OFSArrangeDeliveryDetail_Load:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "TreeView Events"

    ''' <summary>
    ''' 樹結點選擇後
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tvw_2_1_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles Tvw_2_1.AfterCheck, Tvw_1_2.AfterCheck
        Try
            Dim Tvw As TreeView = DirectCast(sender, TreeView)

            If AfterCheckBool = True Then Exit Sub

            Select Case Tvw.Name.ToLower

                Case Me.Tvw_1_2.Name.ToLower

                    AfterCheckNode(e.Node)

                Case Else

            End Select
            'lbTotal.Text = Tvw.CanSelect.ToString.Trim


        Catch ex As Exception
            MessageBox.Show("Tvw_2_1_AfterCheck:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 樹結點選擇後
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tvw_2_1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles Tvw_2_1.AfterSelect, Tvw_3_1.AfterSelect
        Try
            Dim Tvw As TreeView = DirectCast(sender, TreeView)
            Select Case Tvw.Name.ToLower

                Case Me.Tvw_2_1.Name.ToLower

                    TreeNode_AfterSelect_2(e.Node)

                Case Me.Tvw_3_1.Name.ToLower

                    TreeNode_AfterSelect_3(e.Node)

                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("Tvw_2_1_AfterSelect:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 結點選擇前
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tvw_1_1_BeforeCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles Tvw_1_1.BeforeCheck, Tvw_2_1.BeforeCheck
        Try
            Dim Tvw As TreeView = DirectCast(sender, TreeView)
            Select Case Tvw.Name.ToLower
                Case Me.Tvw_1_1.Name.ToLower

                    If e.Node.Level = 0 Then
                        e.Cancel = True
                    Else

                    End If

                Case Me.Tvw_2_1.Name.ToLower

                    If fCheckBool = False Then
                        e.Cancel = True
                    End If

                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("Tvw_1_1_BeforeCheck:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 結點展開前
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tvw_1_1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles Tvw_1_1.BeforeExpand, Tvw_2_1.BeforeExpand, Tvw_3_1.BeforeExpand, Tvw_1_2.BeforeExpand
        Try
            Dim Tvw As TreeView = DirectCast(sender, TreeView)
            Select Case Tvw.Name.ToLower
                Case Me.Tvw_1_1.Name.ToLower
                    Load_TreeNode_1(e.Node)
                Case Me.Tvw_1_2.Name.ToLower
                    Load_TreeNode_1_2(e.Node)
                Case Me.Tvw_2_1.Name.ToLower
                    Load_TreeNode_2(e.Node)
                Case Me.Tvw_3_1.Name.ToLower
                    Load_TreeNode_3(e.Node)
            End Select
        Catch ex As Exception
            MessageBox.Show("Tvw_1_1_BeforeExpand:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    ''' <summary>
    ''' 結點選擇前
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tvw_1_1_BeforeSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles Tvw_1_1.BeforeSelect, Tvw_2_1.BeforeSelect, Tvw_3_1.BeforeSelect, Tvw_1_2.BeforeSelect
        Try
            Dim TView As TreeView = DirectCast(sender, TreeView)
            If e.Node Is Nothing Then Exit Sub

            Select Case TView.Name.ToLower
                Case Me.Tvw_3_1.Name.ToLower
                    If Action = IDServer.IDServer.ActionBtn.ActionEdit Then
                        e.Cancel = True
                        Exit Sub
                    End If
                Case Else

            End Select

            Dim Node As TreeNode = TView.SelectedNode
            If Not Node Is Nothing Then
                Node.ForeColor = Color.Black
            End If
            e.Node.ForeColor = Color.Blue
        Catch ex As Exception
            MessageBox.Show("Tvw_1_1_BeforeSelect:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "Button Events"

#End Region

#Region "Load Controls"

#End Region

#Region "Context Menu"

    ''' <summary>
    ''' 設置右鍵狀態
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub ContextMenuStrip1_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        Try
            Dim Index As Integer = Me.Re_SelectTabIndex()
            ContextMenuEnabled(Index)
        Catch ex As Exception
            MessageBox.Show("ContextMenuStrip1_Opening:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "DataGridView Events"

    ''' <summary>
    ''' PreviewKeyDown
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_3_1_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles DGV_3_1.PreviewKeyDown
        Try
            Select Case e.KeyCode
                Case Keys.Enter
                    If e.Shift = True Then
                        SendKeys.Send("+{Tab}")
                        SendKeys.Send("{F2}")
                    Else
                        SendKeys.Send("{Tab}")
                        SendKeys.Send("{F2}")
                    End If
            End Select
        Catch ex As Exception
            MessageBox.Show("DGV_3_1_PreviewKeyDown:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 繪制行號
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_3_1_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_3_1.RowPostPaint
        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(DGView.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToSingle(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), DGView.RowHeadersDefaultCellStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MessageBox.Show("DGV_3_1_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 行選擇改變後
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_3_1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_3_1.SelectionChanged
        Try
            If Me.IsEditMode = True AndAlso Me.Action = IDServer.IDServer.ActionBtn.ActionEdit Then Exit Sub
            Dim fSaleOrdeNo As String = ""
            Dim fDeliverId As String = ""

            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            If Not DGView.CurrentRow Is Nothing AndAlso DGView.SelectedRows.Count > 0 Then
                fDeliverId = DGView.CurrentRow.Cells("fDeliverId").Value.ToString.Trim & ""
                fSaleOrdeNo = DGView.CurrentRow.Cells("fSaleOrdeNo").Value.ToString.Trim & ""
            End If
            FillDetail_3_1(fDeliverId, fSaleOrdeNo)

            'If Me.TabControl3.SelectedIndex = 1 Then
            FillDataGridDetail(fDeliverId, fSaleOrdeNo, 3)
            'End If
            '
        Catch ex As Exception
            MessageBox.Show("DGV_3_1_SelectionChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DGView_3_2_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGView_3_2.CellDoubleClick
        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            If DGView.ReadOnly = True Then Exit Sub

            If DGView.CurrentCell Is Nothing Then Exit Sub

            Dim ColumnName As String = DGView.Columns(DGView.CurrentCell.ColumnIndex).Name

            Select Case ColumnName.ToLower

                Case "fHouseId".ToLower

                    Dim frm As New Frm_SelectStoreHouse
                    If frm.ShowDialog() = DialogResult.OK Then
                        Dim fHouseId As String = frm.Fcode
                        Dim CheckBool As Boolean = frm.CheckBox1.Checked
                        Dim Dtab As DataTable = DirectCast(DGView.DataSource, DataTable)
                        If CheckBool = True Then
                            For Each Row As DataRow In Dtab.Rows
                                If Row("fGoodsBarCode").ToString.ToLower = "DISCOUNT".ToLower Then

                                Else
                                    Row("fHouseId") = fHouseId
                                End If
                            Next
                            Dtab.AcceptChanges()
                        Else
                            DGView.CurrentCell.Value = fHouseId
                            DGView.Update()
                        End If
                    End If

                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("DGView_3_2_CellDoubleClick:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    Private Sub DGView_3_2_RowValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGView_3_2.RowValidated
        ''記錄行選擇改變
        fRowValidated = True
    End Sub

    '''' <summary>
    '''' 當前Cell 改變時
    '''' </summary>
    '''' <param name="sender"></param>
    '''' <param name="e"></param>
    '''' <remarks></remarks>
    'Private Sub DGView_3_2_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_3_2.CurrentCellChanged
    '    Try
    '        Me.Cursor = Cursors.WaitCursor
    '        Dim DGView As DataGridView = DirectCast(sender, DataGridView)
    '        Dim BarCode As String = ""
    '        If Not DGView.CurrentRow Is Nothing AndAlso Not DGView.CurrentCell Is Nothing Then
    '            BarCode = DGView.CurrentRow.Cells("fGoodsBarCode").Value.ToString.Trim
    '        End If
    '        FillStoreDataGridView(Me.DGView_3_4, BarCode)

    '    Catch ex As Exception
    '        MessageBox.Show("DGView_3_2_CurrentCellChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
    '    Finally
    '        Me.Cursor = Cursors.Default
    '    End Try
    'End Sub

    Private Sub DGView_3_2_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_3_2.SelectionChanged
        Try
            Me.Cursor = Cursors.WaitCursor
            If fCellSelect = False Then Exit Sub
            ''只有改變行時再執行
            'If fRowValidated = True Then
            '    Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            '    Dim BarCode As String = ""
            '    If Not DGView.CurrentRow Is Nothing AndAlso Not DGView.CurrentCell Is Nothing Then
            '        BarCode = DGView.CurrentRow.Cells("fGoodsBarCode").Value.ToString.Trim
            '    End If
            '    FillStoreDataGridView(Me.DGView_3_4, BarCode)
            '    fRowValidated = False
            'End If
        Catch ex As Exception
            MessageBox.Show("DGView_3_2_CurrentCellChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    ''' <summary>
    ''' 行選擇後->加載對應貨品的庫存
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_2_1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_2_1.SelectionChanged
        Try

            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            Dim BarCode As String = ""

            If Not DGView.CurrentRow Is Nothing AndAlso DGView.SelectedRows.Count > 0 Then
                BarCode = DGView.CurrentRow.Cells("fGoodsBarCode").Value.ToString.Trim
            End If

            Select Case DGView.Name.ToLower

                Case Me.DGV_2_1.Name.ToLower
                    If BarCode = "" Then
                        If TypeOf Me.DGV_2_2.DataSource Is DataTable Then
                            CType(Me.DGV_2_2.DataSource, DataTable).Clear()
                        End If
                    Else
                        FillStoreDataGridView(Me.DGV_2_2, BarCode)
                    End If

                Case Me.DGView_3_2.Name.ToLower

            End Select
        Catch ex As Exception
            MessageBox.Show("DGV_2_1_SelectionChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


#End Region

#Region "Value/Text Changed"

    Private Sub txtfSaleOrdeNo_Filter_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtfSaleOrdeNo_Filter.TextChanged
        Try
            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
            If Dtab.Rows.Count <= 0 Then Exit Sub
            Dim Filter As String = "Isnull(fSaleOrdeNo,'') like '%" & Replace_Text(Me.txtfSaleOrdeNo_Filter.Text.Trim) & "%'"
            Dtab.DefaultView.RowFilter = Filter
        Catch ex As Exception
            MessageBox.Show("txtfSaleOrdeNo_Filter_TextChanged:" & ex.Message & ex.Source, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub cbx_AreaCode_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbx_AreaCode.TextChanged
        Try
            If Me.fLoadBool = False Then Exit Sub
            If Me.fTreeSelectChanged = True Then Exit Sub '' 樹結點選擇時不激發事件。
            Dim Dtab As DataTable = DirectCast(Me.DGV_3_1.DataSource, DataTable)
            If Dtab Is Nothing OrElse Dtab.Rows.Count <= 0 Then Exit Sub
            Dim RowFilter As String = ""
            Dim Node As TreeNode = Me.Tvw_3_1.SelectedNode
            If Me.cbx_AreaCode.Text.Trim <> "" AndAlso Not Me.cbx_AreaCode.SelectedValue Is Nothing Then
                RowFilter = "Isnull(fAreaId,'')='" & Me.cbx_AreaCode.SelectedValue & "'"
                Dtab.DefaultView.RowFilter = RowFilter
            Else
                Dtab.DefaultView.RowFilter = "1=1"
            End If

        Catch ex As Exception
            MessageBox.Show("cbx_AreaCode_TextChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "Validating"

#End Region

#Region "Checked Changed"

    ''' <summary>
    ''' 控制日期條件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged
        Dim CheckBox As CheckBox = DirectCast(sender, CheckBox)
        Dim Bool As Boolean = CheckBox.Checked

        Select Case CheckBox.Name.ToLower
            Case Me.CheckBox1.Name.ToLower  ''送貨日期

                Me.dtpfDeliverDateStart.Enabled = Bool
                Me.dtpfDeliverDateEnd.Enabled = Bool

            Case Me.CheckBox2.Name.ToLower ''銷售日期

                Me.dtpStartDate.Enabled = Bool
                Me.dtpEndDate.Enabled = Bool

            Case Else

        End Select
    End Sub

#End Region

#End Region
End Class
